2016-09-22 19 views
0

現在のユーザーと負荷の通知では、Entity FrameworkのはFromUserあるSentNotificationsリストで通知をロードするために作るためにどのよう重複1対多の関係Entity Frameworkの

public class Notification 
{ 
    public virtual int? FromUserId { get; set; } 
    public virtual int? ToUserId { get; set; } 
    public virtual SystemUser FromUser { get; set; } 
    public virtual SystemUser ToUser { get; set; } 
} 

public class SystemUser 
{ 
    public virtual ICollection<Notification> SentNotifications { get; set; } 
    public virtual ICollection<Notification> RecievedNotifications { get; set; } 
} 

をされ、次のように私は2人のエンティティのユーザーとの通知を持っていますReceivedNotificationsリストはToUserです現在のユーザーですか?

答えて

1

片道は、InversePropertyデータ注釈を使用しています。リレーションシップのどちらかの端にアノテーションを配置することもできます。

public class Notification 
{ 
    public int? FromUserId { get; set; } 
    public int? ToUserId { get; set; } 
    [InverseProperty("SentNotifications")] 
    public virtual SystemUser FromUser { get; set; } 
    [InverseProperty("RecievedNotifications")] 
    public virtual SystemUser ToUser { get; set; } 
} 

第2の方法は、あなたの関係を明示的に設定することです。私はそれをテストします、あなたの答えの@octaviocclため

modelBuilder.Entity<Notification>() 
    .HasOptional(l => l.FromUser) 
    .WithMany(p => p.SentNotifications) 
    .HasForeignKey(l=>l.FromUserId); 

modelBuilder.Entity<Notification>() 
    .HasOptional(l => l.ToUser) 
    .WithMany(p => p.RecievedNotifications) 
    .HasForeignKey(l=>l.ToUserId);; 
+0

感謝:あなたは、例えば、あなたのコンテキストのOnModelCreatingメソッドをオーバーライドして、このコードを追加することができます –

関連する問題