我有几个参与一对多和多对多关系的人。实体框架不公开生成的联结表的模型,所以我试图弄清楚如何使用导航属性来生成此查询的等效结果:
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);
答案 0 :(得分:2)
我不知道您的实体和导航属性的名称,但我认为您可以这样做:
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};
答案 1 :(得分:0)
在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);
编辑:定义了上述关系后,您可以使用这样的查询(psudocode):
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 }