Entity Framework 6 中没有联结表的多对多查询

Many-to-Many Query in Entity Framework 6 without Junction Tables

我有几个实体涉及一对多和多对多关系。 Entity framework 不会为生成的联结表公开模型,因此我试图找出如何使用导航属性来生成与此查询等效的结果:

select p.Name, p.Description, p.Version, p.Filename, f.Name as Platform, p.ReleaseNotesURL
from packages p
inner join Platforms f on (f.ID = p.PlatformID)
inner join PackageGroups pg on (pg.Package_ID = p.ID)
inner join Groups g on (g.ID = pg.Group_ID)
inner join GroupCustomers gc on (gc.Group_ID = g.id)
where gc.Customer_ID = @customerId AND p.IsPublished = 1

已解决:感谢octavioccl,我得到了我想要的解决方案:

var request = HttpContext.Request;
var appUrl = HttpRuntime.AppDomainAppVirtualPath;
var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

var items = from s in db.Packages
            join p in db.Platforms on s.PlatformID equals p.ID
            from g in s.Groups
            from c in g.Customers
            where c.ID == customer.ID && s.IsPublished
            select new
            {
                Name = s.Name,
                Description = s.Description,
                Version = s.Version,
                PackageURL = baseUrl + "/PackageFiles/" + s.Filename,
                Platform = p.Name,
                ReleaseNotesURL = s.ReleaseNotesURL
            };

return Json(items.ToList(), JsonRequestBehavior.AllowGet);

我不知道您的实体名称和导航属性,但我认为您可以这样做:

int id=10;
var items = from s in db.Packages
            join p in db.Platforms on s.PlatformID equals p.ID
            from g in s.Groups
            from c in g.Customers
            where c.Id==id && s.Published==1
            select new {Name=s.Name, 
                        Description=s.Description,
                        Version= s.Version,
                        FileName= s.Filename,
                        PlatformName=p.Name,
                        ReleaseNoteUrl=p.ReleaseNoteUrl};

在 OnModelCreating 中尝试这样的事情:

modelBuilder.Entity<PackageGroup>()
            .HasMany(x => x.Groups)
            .WithRequired(x => x.PackageGroups)
            .HasForeignKey(x => x.Group_ID)
            .WillCascadeOnDelete(false);

modelBuilder.Entity<PackageGroup>()
            .HasMany(x => x.Packages)
            .WithRequired(x => x.PackageGroups)
            .HasForeignKey(x => x.Package_ID)
            .WillCascadeOnDelete(false);

编辑:定义了上述关系后,您就可以使用这样的查询(伪代码):

var query = 
    from g in db.groups
    from pg in g.packageGroups
    from p in pg.packages
    where g.Name = "Something" && p.Version = 1
    select new { yada yada }