如何在 Entity Framework 代码优先中处理自引用?

How to handle self references in Entity Framework code-first?

这些是我的模型(简化版):

public User()
{
        Friends = new HashSet<User>();
        Subscriptions = new HashSet<Subscription>();
        Tasks = new HashSet<Task>();
        Invitations = new HashSet<Invitation>();
        Events = new HashSet<Event>();
}

public Guid UserId { get; set; }
public DateTime MemberSince { get; set; }

[StringLength(450)]
[Index("UserNameIndex", IsUnique = true)]
public string NickName { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAdress { get; set; }        
public string HashedPassword { get; set; }

public virtual ProfilePicture ProfilePicture { get; set; }

public bool Validated { get; set; } 

ICollection<Event> Events { get;  set; }
ICollection<User> Friends { get;  set; }

Event 型号:

public class Event
{    
    public string EventName { get; set; }
    public Guid EventId { get; set; }
    public Guid UserId { get; set; } 
    public DateTime? Time { get; set; }
    public string Location { get; set; }
    public DateTime? EventDate { get; set; }        
    public virtual User User { get; set; }

    public ICollection<User> Participants { get; internal set; }        
}

创建模型如下:

modelBuilder.Entity<User>().HasKey(u => u.UserId);
modelBuilder.Entity<User>().
             HasMany<User>(u => u.Friends).
             WithMany();

modelBuilder.Entity<User>().
             HasMany<Event>(u => u.Events).
             WithMany();

现在的问题如下:我的 table 看起来像这样:

关系好像不太对...

User table:

Event table:

自动创建UserEvents:

现在我期望的是在那里需要创建一个新事件 (UserId)。我在 Events table 中获得了一个新条目 + 在 UserEvents 中获得了一个新条目....

我在这里错过了什么?

用户和事件之间有两种不同的关系。一对多关系和多对多关系。

第一种是事件和事件创建者之间的一对多关系(Event上的user和userid属性) 当您使用所需的 UserId 添加新的 Event 时,自动创建的 UserEvents table 中不会创建记录,因为您在此处具有一对多关系。因此,简单地使用用户标识创建事件不会导致 UserEvents table.

中的记录

第二个是Event和它的参与者之间的多对多关系。当您添加有参与者的活动时。还会有记录也插入到 UserEvents table。只有参与者会出现在 UserEvents table 中。但是,您应该创建多对多映射并参考您的 属性 事件参与者 class 以实现此目的。

modelBuilder.Entity<User>().HasMany<Event>(u => u.Events).WithMany(m => m.Participants);