如何使用EntityFramework5Fluent API设置列名不同的外键
本文关键字:何使用 EntityFramework5Fluent API 设置 | 更新日期: 2023-09-27 18:23:52
我正在尝试使用Fluent API(实体框架v5)在以下域类之间建立外键关系:
public partial class User
{
public long UserID { get; set; }
public string UserName { get; set; }
}
public partial class AccountGroup : BaseEntity
{
public long AccountGroupID { get; set; }
public string Name { get; set; }
public long ModifiedBy { get; set; }
public virtual User User { get; set; }
}
流利的API
builder.Entity<User>().HasKey(p => p.UserID); //Set User Id as primary key
builder.Entity<AccountGroup>().HasKey(x => x.AccountGroupID); //SetAccountGroupId as PK
我不知道如何使用流利的API设置User.UserId和AccountGroup.ModifiedBy列之间的关系。我可以通过Data Annotation来做到这一点,但我正在寻找一个使用fluent api 的解决方案
从实体中删除ModifiedBy属性:
public partial class AccountGroup
{
public long AccountGroupID { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
}
然后像这样映射外键:
builder.Entity<AccountGroup>()
.HasRequired(x => x.User)
.WithMany()
.Map(m => m.MapKey("ModifiedBy"));
如果外键应为null,请改用HasOptional:
builder.Entity<AccountGroup>()
.HasOptional(x => x.User)
.WithMany()
.Map(m => m.MapKey("ModifiedBy"));
您也不需要像现在这样指定主键。实体框架将按照惯例发现这些。