如何在实体中设置两个字段(在同一表中或不同表中)之间的单向关系

本文关键字:关系 之间 两个 设置 实体 字段 | 更新日期: 2023-09-27 18:10:54

我使用CodeFirst进行开发。对于我的实体中的所有模型类,我有一个名为CommonFields的基类

public class CommonFields
{
    public int Status { get; set; }
    public DateTime CreatedOn { get; set; }
    public int CreaedBy { get; set; }
    public DateTime ModifiedOn { get; set; }
    public int ModifiedBy { get; set; }
}

和,例如。我有两个类,比如

public class Employee : CommonFields
{
    public int Id { get; set; }
    public string Name { get; set; }
    //Other properties
}
public class User : CommonFields
{
    public int Id { get; set; }
    public string Name { get; set; }
    //Other properties
}

如何设置CreatedBy &ModifiedBy to User表。我只需要一个方向映射。

我需要得到用户信息,当我写objEmployee。CreatedUser

谢谢。

如何在实体中设置两个字段(在同一表中或不同表中)之间的单向关系

public class CommonFields
{
    public int Status { get; set; }
    public DateTime CreatedOn { get; set; }
    public int? CreatedById { get; set; }
    public virtual User CreatedBy { get; set; }
    public DateTime ModifiedOn { get; set; }
    public virtual User ModifiedBy { get; set; }
    public int? ModifiedById { get; set; }
}

,你必须定义DbContext中所有派生实体的关系

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Entity<User>().HasOptional(x => x.CreatedBy).WithMany().HasForeignKey(x => x.CreatedById).WillCascadeOnDelete(false);
    mb.Entity<User>().HasOptional(x => x.ModifiedBy).WithMany().HasForeignKey(x => x.ModifiedById).WillCascadeOnDelete(false);
    mb.Entity<Employee>().HasOptional(x => x.CreatedBy).WithMany().HasForeignKey(x => x.CreatedById).WillCascadeOnDelete(false);
    mb.Entity<Employee>().HasOptional(x => x.ModifiedBy).WithMany().HasForeignKey(x => x.ModifiedById).WillCascadeOnDelete(false);
}
编辑:

或者你可以用TPH。然后你的模型创建看起来像这样

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Entity<CommonFields>().
            .Map(x => x.ToTable("Users"))
            .Map<User>(x => x.Requires("__type").HasValue(1)
            .Map<Employee>(x => x.Requires("__type").HasValue(2);
    mb.Entity<CommonFields>().HasOptional(x => x.CreatedBy).WithMany().HasForeignKey(x => x.CreatedById).WillCascadeOnDelete(false);
    mb.Entity<CommonFields>().HasOptional(x => x.ModifiedBy).WithMany().HasForeignKey(x => x.ModifiedById).WillCascadeOnDelete(false);
}