1

之間的兩個關係,我有兩個實體:用戶配置和收件箱管理2個實體

這是我UserProfile代碼:

public partial class UserProfile { 
    public int Id { get; set; } 
    public string UserName { get; set; } 
    public string Password { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    //-------------------------- 
    public virtual ICollection<Messages.Inbox> Inboxes { get; set; } 
} 

public partial class UserProfile { 
    public static void Configure(DbModelBuilder mb) { 
     mb.Entity<UserProfile>().HasKey(up => up.Id); 
    } 
} 

這是我Inbox代碼:

public partial class Inbox { 
    public int Id { get; set; } 
    public int UserId { get; set; }//FK to userProfile 
    public Accounts.UserProfile User { get; set; } 
    public DateTime MessageDateTime { get; set; } 
    public string Context { get; set; } 
    public int SenderId { get; set; }//FK to userProfile 
    public Accounts.UserProfile Sender { get; set; } 
} 

public partial class Inbox { 
    public static void Configure(DbModelBuilder mb) { 
     mb.Entity<Inbox>().HasKey(up => up.Id); 
     mb.Entity<Accounts.UserProfile>().HasMany(up => up.Inboxes) 
      .WithRequired(p => p.User) 
      .HasForeignKey(p => p.UserId); 
     mb.Entity<Accounts.UserProfile>().HasMany(up => up.Inboxes) 
      .WithRequired(p => p.Sender) 
      .HasForeignKey(p => p.SenderId); 
    } 
} 

如何管理InboxUserProfile之間的這兩個關係?

+0

我不確定你在這裏的「管理」是什麼意思,但是看看你的映射,當你添加一個新的收件箱實體時使用EF,例如你需要設置用戶/發件人屬性,一旦你設置了父收件箱的objectState將被「添加」,EF將標記要添加的導航屬性,並且會將3個實體添加到數據庫,1個收件箱和2個用戶配置文件。這種情況對您的業務有效嗎? – 2014-10-18 02:56:00

+0

@ omar.alani,no,userId和senderId對於UserProfile只是FK,例如我們有一個id爲'5'的userProfile和一個Id爲'8'的userProfile,並且在收件箱中userid是5,senderid是8 – 2014-10-18 03:33:37

+0

是的,所以從技術上講,你只能設置SenderId/UserId和收件箱可以正確保存,但我以前的方案仍然在技術上是有效的,這意味着你仍然可以從收件箱實體添加用戶,如果你不希望這種情況發生,你可能會單獨設置用戶,切勿通過您的服務暴露發件人/用戶屬性。 – 2014-10-18 03:52:18

回答

0

如果你有一個你公開給用戶/ ui添加收件箱的DTO,該dto不應該包含用戶/發件人屬性,只是Ids SenderId/UserId,但保留在收件箱實體中,因爲你需要從收件箱實體加載有關用戶/發件人的一些詳細信息,因此可以使用Entity-framework將其包含在UserProfile表中,而不是加入UserProfile表。希望有所幫助。