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

时间:2013-04-26 07:20:41

标签: c# entity-framework ef-code-first

我正在使用CodeFirst进行开发。对于我的Entity中的所有模型类,我有一个名为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

时需要获取用户信息

感谢。

1 个答案:

答案 0 :(得分:0)

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