[英]Entity Framework Map With Fake Foreign Key Property
我的模特:
class FooEntity
{
[Key]
int Id { get; set; }
[ForeignKey("Bar"), Column("other_id")]
int OtherId { get; set; } // <-- This should be the FK
virtual BarEntity Bar { get; set; }
}
class BarEntity
{
[Key]
int Id { get; set; }
[Column("other_id")]
int OtherId { get; set; } // <-- This is the other side of the FK
}
本質上,我想重現此SQL:
select *
from foo f
left join bar b on b.other_id = f.other_id -- AND other conditions to "guarantee" uniqueness
但是使用模型構建配置:
modelBuilder.Entity<FooEntity>()
.HasOptional(f => f.Bar)
.WithRequired()
.Map(m => m.MapKey("other_id"))
.WillCascadeOnDelete(false);
我最終收到錯誤消息:“類型中的每個屬性名稱都必須是唯一的。屬性名稱'other_id'已經定義。” 但是當我添加:
modelBuilder.Entity<BarEntity>().Ignore(b => b.OtherId);
在其他配置之前,我收到錯誤消息:“ LINQ to Entities不支持指定的類型成員'OtherId'。僅支持初始化程序,實體成員和實體導航屬性。”
那么我怎樣才能使它正常工作呢? 絕對不能更改基礎數據結構。
我建議您省略FK關系,並且當您需要手動檢索兩個實體時,請在您的Linq / Lambda語句中包括該聯接。
您想要完成的任務沒有捷徑可走。 您將需要手動創建查詢,類似於以下內容:
dbContext.Foos
.GroupJoin(
dbContext.Bars,
f => f.OtherId,
b => b.OtherId,
( foo, bars ) => new { foo, bars } )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.