[英]Many-to-Many Query in Entity Framework 6 without Junction Tables
我有幾個實體參與一對多和多對多關系。 實體框架沒有公開生成的聯結表的模型,所以我試圖弄清楚如何使用導航屬性來產生與此查詢等效的結果:
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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.