简体   繁体   English

一对多关系实体框架重复

[英]Duplicated one-to-many relationship Entity Framework

I have two entities user and notification as following 我有两个实体用户和通知如下

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

How to make Entity Framework to load notifications in SentNotifications list which is FromUser is the current user and load notifications in ReceivedNotifications list which is ToUser is the current user? 如何使实体框架加载在通知中SentNotifications列表,它是FromUser是在当前用户和负载通知ReceivedNotifications列表,它是ToUser是当前用户?

One way is using InverseProperty Data annotation. 一种方法是使用InverseProperty数据注释。 You can place the annotations on either end of the relationship (or both ends if you want). 您可以将注释放置在关系的任一端(如果需要,也可以放置在两端)。

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

The second way is using Fluent Api to configure your relationships explicitly. 第二种方法是使用Fluent Api显式配置您的关系。 You could, for example, override OnModelCreating method of your context and add this code: 例如,您可以覆盖上下文的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);;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM