C# 实体框架-反向属性关系?

C# 实体框架-反向属性关系?,c#,entity-framework,entity-framework-core,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 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; }
}
公共类组织{
公共Guid Id{get;set;}
//只有一个用户作为公司的管理员
公共用户AdminUser{get;set;}
//与公司相关的所有用户(包括管理员)
公共ICollection用户{get;set;}
}
公共类用户{
公共Guid Id{get;set;}
//每个用户必须与一个组织关联。
[外键(“组织”)]
公共Guid组织ID{get;set;}
公共组织{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);
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(o=>o.Users)
.有一个(u=>u.Organization);
modelBuilder.Entity()
.HasOne(o=>o.AdminUser)
.有一个(u=>u.Organization);
}
有关fluent配置的更多信息:。
大约一对多关系:。关于反向导航属性:。

所以用户从来不是多个组织的成员,也从来不是多个组织的管理员,对吗?管理员是否必须属于他担任管理员的同一组织?嗨,Grek。是的,没错。如果有意义的话,组织将充当管理员用户的扩展。在现阶段,我不打算在组织和用户之间建立M-M关系。您所说的“管理用户的扩展”是什么意思?你会在OOP中从
User
继承
Organization
吗?谢谢Diana,我目前正在使用Fluent配置重命名标识表和级联密钥删除。感谢您提供的示例代码,我将试一试。不客气。我编辑了答案以修正一些错误,请检查最终版本。。