实体框架代码第一:一对多和多对多关系到同一个表 [英] Entity Framework Code First: One-to-Many and Many-to-Many relationships to same table

查看:102
本文介绍了实体框架代码第一:一对多和多对多关系到同一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个用户模型和一个事件模型。事件有一个创建者(用户)并且有参与者(用户),所以事件与用户有一对多关系,并且与同一个表的多对多关系。



我首先是一对一的关系,如下所示:

 公共课活动
{
...
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆