以下是我的域名实体
public class User
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public RoleType RoleType { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
我已将 RoleType 设为复杂类型(以实现枚举映射)。所以我可以使用context.Users.FirstOrDefault(u => u.RoleType.Value == (long)RoleTypes.Admin)
之类的东西
RoleTypes.Admin
是到角色实体的枚举映射
public class RoleType
{
public int Value { get; set; }
// And all the implicit operators to map with enum
}
然后我使用流畅的api
创建了一个映射public class RoleTypeMapping : ComplexTypeConfiguration<RoleType>
{
public RoleTypeMapping()
{
Property(r => r.Value)
.HasColumnName("RoleId"); // To make sure that in RoleType property of User EF entity maps to an int column [RoleId] in database (table [Users])
}
}
使用fluent-api,我想在[Users]表中为[Users]创建一个外键关联。[RoleId]引用[Role]。[Id]。请任何人都可以为我提供指导,以实现这个
我厌倦了添加Role类型的属性并通过fluent-api创建映射,但是EF创建了另一个列Role_Id并使其成为外键。我希望现有的[RoleId]列(复杂类型)是外键
答案 0 :(得分:3)
这是不可能的。如果要与Role表关联,则必须放弃类似enum的方法并定义Users实体,如:
public class User
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public Role Role { get; set; }
}
首先,关系不是枚举,复杂类型不能包含导航属性(以及外键)。