[英]How to create a model with self reference in Entity Framework Code-First?
[英]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();
现在的问题如下:我的表如下所示:
看来这种关系不是应该的方式...
User
表:
Event
表:
自动创建的UserEvents
:
现在,我期望的是在那里需要创建新事件(UserId)时。 我在事件表中获得了一个新条目,在用户事件中获得了一个新条目。
我在这里想念什么?
用户和事件之间有两种不同的关系。 一对多关系和多对多关系。
第一个是事件与事件的创建者之间的一对多关系(Event上的user和userid属性)当您添加具有所需UserId的新Event时,不会在自动创建的记录中创建任何记录UserEvents表,因为您在此处具有一对多关系。 因此,仅使用用户ID创建事件将不会导致UserEvents表中的记录。
第二个是Event与参与者之间的多对多关系。 与参与者添加活动时。 还将在UserEvents表中插入记录。 只有参与者会出现在UserEvents表中。 但是,您应该通过引用Event类中的属性“参与者”来创建多对多映射,以实现此目的。
modelBuilder.Entity<User>().HasMany<Event>(u => u.Events).WithMany(m => m.Participants);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.