c# - Entity Framework - 反向属性关系?

标签 c# entity-framework entity-framework-core

我无法理解如何完成以下关系:

public class Organisation {

    public Guid Id { get; set; }

    // Have a single user as an administrator of a company
    public User AdminUser { get; set; }

    // All users associated with the company (including the admin)
    public ICollection<User> Users { get; set;}
}

public class User {

    public Guid Id { get; set; }

    // Each User must be associated with an Organisation.
    [ForeignKey("Organisation")]
    public Guid OrganisationId { get; set; }
    public Organisation Organisation { get; set; }
}

这是可以通过逆属性来完成的事情吗?我知道它们是定义相同实体之间多种关系的解决方案,但我正在努力了解如何针对我的情况进行设置。有人可以帮忙提供示例代码吗?

提前致谢。

最佳答案

除了属性注解,你还可以使用流畅的配置。它们比注释更强大、更灵活,并允许您配置相同实体之间的多种关系。

您可以在 DbContext 类的 OnModelCreating 方法中定义配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Organisation>()
        .HasMany(o => o.Users)
        .WithOne(u => u.Organisation);

   modelBuilder.Entity<Organisation>()
        .HasOne(o => o.AdminUser)
        .WithOne(u => u.Organisation);
}

有关流畅配置的更多信息:here . 关于一对多关系:here .关于反向导航属性:here .

关于c# - Entity Framework - 反向属性关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48550231/

相关文章:

C# Process Start 需要带双引号的参数 - 它们消失了

c# - LINQPad 如何引用其他类,例如LINQ in Action 示例中的书籍

c# - 检查实体是否在 Code First 中的其他实体中有引用

c# - EF、ASP.NET Web API 和 JSON.NET - 返回限制层次结构

c# - gtest (C++) 和 nunit (C#) 中双重比较的区别

c# - 在游戏模式下加载对象

c# - Entity Framework 迁移错误

entity-framework-core - Entity Framework - 使用派生类型方法有条件地查询相关实体

entity-framework-core - 使用 Microsoft.EntityFrameworkCore.InMemory 测试并发 token

entity-framework-core - EF Core 中的 IsNumeric