小编典典

多个左联接的LINQ方法语法

sql

需要将三个表连接在一起。

Table [Package]

ID (int)
ContainerID (int)
Code (string)
Code2 (string)


Table [UserHasPackages]

UserID (Comes from Identity tables) (string)
PackageID (int)


Table [Container]

ID (int)
Name (string)
Description (string)

进入一个表示要在我的视图中显示的对象的视图模型:

public class CustomViewModel
{
    public int ID { get; set; }
    public string Name { get; set; } // Container.Name
    public string Code { get; set; } // Package.Code
    public string Code2 { get; set; } // Package.Code2
}

但是我在加入时遇到了问题:

List<CustomViewModel> list = new List<CustomViewModel>();

        list = context.Packages.Join(
            context.Containers,
            p => p.ContainerID,
            c => c.ID,
            (p, c) => new { p, c})
        .Join(                                 //error is here
            context.UserHasPackages,
            a => a.p.ID,
            b => b.ApplicationUserId,
            (a, b) => new { a, b })
        .Select(f => new CustomViewModel
        {
            ID = f.p.ID,
            Name = f.c.Name,
            Code = f.p.Code,
            Code2 = f.p.Code2
        }).ToList();

Type arguments for method cannot be inherited from the usage. Try specifying the type arguments explicitly.

还有另一种方法(如上所述)进行两个联接吗?


解决方案

基于方法的语法在这里是行不通的,必须与查询语法一起使用:

var query = (from package in context.Packages
        join container in context.Containers on package.ContainerID equals container.ID
        join userHasPackage in context.UserHasPackages on package.ID equals userHasPackage.PackageID
        where userHasPackage.UserID == "SomeUser"
        select new CustomViewModel
        {
            ID = package.ID,
            Name = container.Name,
            Code = package.Code,
            Code2 = package.Code2
        }).ToList();

阅读 230

收藏
2021-05-30

共1个答案

小编典典

我假设您想加入UserHasPackages表,因为您想过滤特定用户的结果(我只是输入了’SomeUser’,因为我不确定’UserHasPackages.ApplicationUserId’的来源)不包含在视图模型中。

我相信类似以下内容的方法应该起作用:

var list = context.Packages
    .Join(context.Containers, p => p.ContainerID, c => c.ID, (p, c) => new { p, c })
    .Join(context.UserHasPackages, pc => pc.p.ID, u => u.PackageID, (pc, u) => new { pc.p, pc.c, u })
    .Where(pcu => pcu.u.UserID == "SomeUser")
    .Select(pcu => new
    {
        pcu.p.ID,
        pcu.c.Name,
        pcu.p.Code,
        pcu.p.Code2
    });

您也可以使用查询语法来做到这一点:

var query = from package in context.Packages
            join container in context.Containers on package.ContainerID equals container.ID
            join userHasPackage in context.UserHasPackages on package.ID equals userHasPackage.PackageID
            where userHasPackage.UserID == "SomeUser"
            select new
            {
                package.ID,
                container.Name,
                package.Code,
                package.Code2
            };
2021-05-30