猿问

如何设置具有两个外键的实体?

我有一个实体,该实体有两个指向其自己的表的外键。看起来是这样的:


public class SystemUser : BaseModel

{

    [Column("SystemUserId")]

    public override Guid ID { get; set; }


    public string Username { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public string MobilePhone { get; set; }

    public Guid? MobilePhoneProviderId { get; set; }

    public virtual MobilePhoneProvider MobilePhoneProvider { get; set; }

    public Guid? ManagerId { get; set; }

    public virtual SystemUser Manager { get; set; }

    public Guid? AdminAssistantId { get; set; }

    public virtual SystemUser AdminAssistant { get; set; }


    public bool IsActive { get; set; }

    public bool SendEmail { get; set; }


    public string FinaleUsername { get; set; }

    public string FinalePassword { get; set; }

    public int? FloatUserId { get; set; }


    public Guid? SystemUserTypeId { get; set; }

    public virtual SystemUserType SystemUserType { get; set; }

    public Guid? SystemUserJobFunctionId { get; set; }

    public virtual SystemUserJobFunction SystemUserJobFunction { get; set; }

    public Guid? SystemUserJobRoleId { get; set; }

    public virtual SystemUserJobRole SystemUserJobRole { get; set; }

    public Guid? SystemUserLocationId { get; set; }

    public virtual SystemUserLocation SystemUserLocation { get; set; }


    public virtual ICollection<SystemUserRole> Roles { get; set; }

}

注意AdminAssistant和Manager属性。但是,这给了我以下错误:


无法确定类型'SystemUser'和'SystemUser'之间的关联的主要终点。必须使用关系流利的API或数据注释显式配置此关联的主要端。


如果我删除其中的一个(无论哪个,都没关系),它都可以正常工作,但是由于某种原因,对于同时拥有它们,我感到困惑。我尝试ForeignKey在每个属性上添加属性,以及使用流畅的API进行如下配置


两者都不起作用。有什么办法可以做到吗?


仅供参考,我没有使用Code First。我正在手动编写数据库脚本,仅使用EF作为ORM。不知道这些信息是否相关,但我想还是会给它。


qq_笑_17
浏览 200回答 1
1回答

MMMHUHU

看起来您会想要包含类似ICollection<SystemUser> ManagedUsers {get; set;}ICollection<SystemUser> AdminAssistedUsers {get; set;}然后,您应该可以执行以下操作:modelBuilder.Entity<SystemUser>()&nbsp; &nbsp; &nbsp; &nbsp; .HasOptional(x => x.Manager)&nbsp; &nbsp; &nbsp; &nbsp; .WithMany(x => x.ManagedUsers)&nbsp; &nbsp; &nbsp; &nbsp; .HasForeignKey(x => x.ManagerId)&nbsp; &nbsp; &nbsp; &nbsp; .WillCascadeOnDelete(false);modelBuilder.Entity<SystemUser>()&nbsp; &nbsp; &nbsp; &nbsp; .HasOptional(x => x.AdminAssistant)&nbsp; &nbsp; &nbsp; &nbsp; .WithMany(x => x.AdminAssistedUsers)&nbsp; &nbsp; &nbsp; &nbsp; .HasForeignKey(x => x.AdminAssistantId)&nbsp; &nbsp; &nbsp; &nbsp; .WillCascadeOnDelete(false);
随时随地看视频慕课网APP
我要回答