entity-framework - Entity Framework 代码优先 : One-to-Many and Many-to-Many relationships to same table

标签 entity-framework ef-code-first code-first entity-framework-migrations

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

我首先有这样的一对多关系:

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; }
      ...
}

如果我删除一对多关系,那么迁移会成功生成多对多关系。

有没有办法只用数据注释来做到这一点?

最佳答案

英孚不知道在哪里User.Events必须映射到。可能是 Event.CreatedBy或者它可以是 Event.Users .两者都会产生一个有效的模型。您必须通过应用 [InverseProperty] 给 EF 一点提示您想要什么。属性:

public class User
{
    ...
    [InverseProperty("Users")]
    public virtual ICollection<Event> Events { get; set; }
    ...
}

关于entity-framework - Entity Framework 代码优先 : One-to-Many and Many-to-Many relationships to same table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121460/

相关文章:

entity-framework - Linq-to-SQL 和 Entity Framework 在同一个项目中?

entity-framework - SQL Profiler 在读取 IEnumerable 列表之前显示查询

entity-framework - EntityFramework Migration级联删除参数

entity-framework - 强制 EF 4.1 Code First 将附加实体视为已修改

c# - 如何使用 EF 5 存储枚举列表

entity-framework - EF SaveChanges() 抛出异常 'The EntityKey property can only be set when the current value of the property is null'

c# - Entity Framework TPH 在抽象基类和空继承类场景中更改鉴别器列

c# - LINQ 和 Entity Framework - 避免子查询

c# - 与连接(桥接)表的一对多关系

具有类似于 ADO.NET Entity Framework 代码优先功能的 PHP ORM 框架?