下面是我的模型:如何通過Fluent API Entity Framework定義多對多關係?
public class TMUrl
{
//many other properties
//only property with type Keyword
public List<Keyword> Keywords{get;set;}
}
public class Keyword
{
//many other properties
//only property with type TMUrl
public List<TMUrl> Urls{get;set;}
}
所以很明顯,無論是實體有許多一對多的關係。 我選擇了流暢的API來講述即
modelBuilder.Entity<TMUrl>
.HasMany(s => s.Keywords)
.WithMany(s => s.URLs).Map(s =>
{
s.MapLeftKey("KeywordId");
s.MapRightKey("UrlId");
s.ToTable("KeywordUrlMapping");
});
這種關係的實體框架,但是當我做
url.Keywords.Add(dbKey); //where url is object of TMUrl,
//dbKey is an existing/new object of Keyword
db.SaveChanges();
我得到異常
An error occurred while saving entities that do not expose foreign key
properties for their relationships....
的InnerException:
The INSERT statement conflicted with the FOREIGN KEY constraint
"KeywordMaster_Keyword". The conflict occurred in database "DbName",
table "dbo.KeywordMaster", column 'Id'.The statement has been terminated.
,但是當我從其他人添加配置時,一切正常。 即
modelBuilder.Entity<KeyWord>
.HasMany(s => s.URLs)
.WithMany(s => s.Keywords)
.Map(s =>
{
s.MapLeftKey("KeywordId");
s.MapRightKey("UrlId");
s.ToTable("KeywordUrlMapping");
});
爲什麼?爲什麼我必須從兩個實體中添加配置,其中我讀過here和其他許多地方,其中一個實體應該配置。
什麼情況下,我應該爲兩個關係中涉及的實體添加配置?
我需要了解這一點。爲什麼。請幫忙。
「*有關詳細信息,請參閱InnerException *」。你是否?對於這個很少有用的例外,內部例外是非常重要的。 – Slauma 2013-05-10 21:16:31
@Slauma,我已經用內部異常更新了這個問題,但請注意,從兩側添加關係都會使其工作。 – 2013-05-10 21:43:38
有趣的問題是,如果*僅*第二個映射(沒有第一個映射)會使它工作。如果是的話,我會懷疑映射表中的'KeywordId'列實際上是表'URLs'而不是'Keywords'的外鍵。 (只有當這是一個具有手動創建關係的現有數據庫時纔可能,而不是如果您使用Code-First創建了數據庫。) – Slauma 2013-05-10 21:50:54