我正在使用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
时需要获取用户信息感谢。
答案 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);
}