重复的一对多关系实体框架

时间:2016-09-22 16:43:23

标签: c# entity-framework entity-framework-6

我有两个实体用户和通知如下

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; }
}

如何使实体框架在SentNotifications列表中加载FromUser列表中的通知ReceivedNotifications当前用户和ToUser列表中的加载通知#define SWAP(x) (((x) << 8) | ((x) >> 8))) char* foo(char* data, size_t len16) { int align = reinterpret_cast<uintptr_t>(data) % sizeof(uint16_t); if (align == 0) { uint16_t* data16 = reinterpret_cast<uint16_t*>(data); for (size_t i = 0; i < len16; i++) { data16[i] = SWAP(data16[i]); } } else { throw "Unaligned"; } return data; } 是当前用户?

1 个答案:

答案 0 :(得分: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; }
}

第二种方法是使用Fluent Api明确配置您的关系。例如,您可以覆盖上下文的OnModelCreating方法并添加以下代码:

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);;