实体框架代码第一:一对多和多对多关系到同一个表 [英] Entity Framework Code First: One-to-Many and Many-to-Many relationships to same table
问题描述
我首先是一对一的关系,如下所示:
公共课活动
{
...
public int CreatedById {get;组; }
public virtual User CreatedBy {get;组; }
...
}
然后当我添加了很多 - 很多关系,迁移不会产生多对多的关系:
公共类用户
{
...
public virtual ICollection< Event>活动{get;组; }
...
}
公共类事件
{
...
public int CreatedById {get;组; }
public virtual User CreatedBy {get;组; }
public virtual ICollection< User>用户{get;组; }
...
}
如果我删除一对一,许多关系,然后移植会成功生成多对多关系。
有没有办法只用数据注释?
EF不知道哪里 User.Events
必须映射到。它可以是 Event.CreatedBy
或它可以是 Event.Users
。两者都会产生一个有效的模型。您必须通过应用 [InverseProperty]
属性给予EF一点提示:
code> public class User
{
...
[InverseProperty(Users)]
public virtual ICollection< Event>活动{get;组; }
...
}
I have a User model and a Event model in my project. The Event has a creator(User) and has participant(Users) so Event has a one-to-many relationship with User and also a many-to-many relationship to the same table.
I had first the one-to-many relationship like this:
Public class Event
{
...
public int CreatedById { get; set; }
public virtual User CreatedBy { get; set; }
...
}
Then when I added the many-to-many relationship the migration doesn't generate the many to many relationship:
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; }
...
}
If I remove the one-to-many relationship then the migration generates the many-to-many relationship successfully.
Is there a way to do this with only data annotations?
EF doesn't know where User.Events
has to be mapped to. It could be Event.CreatedBy
or it could be Event.Users
. Both would result in a valid model. You must give EF a little hint what you want by applying the [InverseProperty]
attribute:
public class User
{
...
[InverseProperty("Users")]
public virtual ICollection<Event> Events { get; set; }
...
}
这篇关于实体框架代码第一:一对多和多对多关系到同一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!