我有一个用户模型,并在自己的项目中事件模型。 事件具有创建者(用户),并具有参与者(用户),以便事件与用户的一对多的关系,并且还以相同的表中的多对多的关系。
我第一次在一到许多这样的关系:
Public class Event
{
...
public int CreatedById { get; set; }
public virtual User CreatedBy { get; set; }
...
}
然后,当我添加了许多一对多的关系迁移不会产生多对多的关系:
Public class User
{
...
public virtual ICollection<Event> Events { get; set; }
...
}
Public class Event
{
...
public int CreatedById { get; set; }
public virtual User CreatedBy { get; set; }
public virtual ICollection<User> Users { get; set; }
...
}
如果删除了一个一对多的关系,那么迁移产生许多一对多的关系成功。
有没有办法,只有数据注解来做到这一点?
EF不知道在哪里User.Events
已经被映射到。 这可能是Event.CreatedBy
或者它可能是Event.Users
。 两者会产生一个有效的模式。 你必须给EF你想通过应用什么小提示[InverseProperty]
属性:
public class User
{
...
[InverseProperty("Users")]
public virtual ICollection<Event> Events { get; set; }
...
}
随着代码第一种方式,我总是建议使用流利的API,而不是使用DataAnnotations,它会自动使用一些转换。
这样一来,你就知道你做了什么确切的配置。
如果我是你,这里是我会用什么:
public class EventMap : EntityTypeConfiguration<Event>
{
public EventMap()
{
this.HasRequired(m => m.CreatedBy) // envent must have a creator
.WithMany() // a user can have 0,1 or more events created by him
.HasForeignKey(m => m.CreatedById) // specify property to be used as FK
.WillCascadeOnDelete(true); // delete all events created by user if that specific user is deleted
this.HasMany(m=>m.Users) // an event can have 0,1 or more participants
.WithMany(m=>m.Events) // a user can be a participant in 0,1 or more events
.Map(m => m.MapLeftKey("EventId").MapRightKey("UserId")); // this will generate intermediate table to hold participant information - dbo.EventUser with EventId & UserId
// Cascade Delete is always true for Many to Many mapping. however, it doesn't delete entry in other table, it deletes entry in Joined Table only.
}
}
文章来源: Entity Framework Code First: One-to-Many and Many-to-Many relationships to same table