2013-03-25 94 views
0

我有我有很多的麻煩映射右以下2個實體關係(使用流暢API)EF代碼優先配置 - 連接表的dilemna

基本上,User既可以是貸款和借款人Item。換句話說Item可以由多個User s爲單位借用,但只能由一個User

public class User { 
    public int UserId { get; set; } 

    public virtual ICollection<Item> ItemsOwned { get; set; } 
    public virtual ICollection<Item> ItemsBorrowed{ get; set; } 
} 

public class Item { 
    public int ItemId { get; set; } 
    public virtual User ItemOwner{ get; set; } 
    public virtual ICollection<User> ItemBorrowers { get; set; } 
} 

所擁有看起來我需要一個一對多也有許多一對多。 我試過無數次的配置,我覺得我只是迷惑自己。

如何獲得正確的關係?我需要一個連接表嗎?

回答

1

這看起來不錯的第一樣子(什麼@Jayantha提出,如果它不夠直應該做的) - 儘管通常你有一個「項目」在借來的有一次(所以那也是一對多)。

如果你正在尋找一個'借來的'物品的歷史(這使得它的多對多) - 那麼你需要製作一個帶有附加標誌的手工索引表(如active等) 。

對於更復雜的場景,請查看我剛纔提到的這些詳細示例 - 它包含大部分可能需要的映射。

Many to many (join table) relationship with the same entity with codefirst or fluent API?

Code First Fluent API and Navigation Properties in a Join Table

EF code-first many-to-many with additional data

1

您需要創建這樣的映射,

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 

     modelBuilder.Entity<Item>().HasRequired(i=>i.ItemOwner).WithMany(u=>u.ItemsOwned);   
     modelBuilder.Entity<Item>().HasMany(i=>i.ItemBorrowers).WithMany(u=>u.ItemsBorrowed);   
} 
+0

謝謝你的答案。這與我在使用Map的其他示例中看到的多對多策略有何不同(mc => {/ * MapLeftKey/MapRightKey/ToTable * /});?我正在嘗試你的答案。 – parliament 2013-03-25 01:43:36

+0

似乎沒有爲獲得Multiplicity的多對多部分工作,但在'Item_ItemBorrowers'關係中的角色'Item_ItemBorrowers_Source'中無效。主體角色的多重性的有效值爲'0..1'或'1'。有任何想法嗎? – parliament 2013-03-25 03:22:11

+0

完成了與NSGaga描述的連接表。 – parliament 2013-03-25 05:51:37