【发布时间】:2018-12-08 10:45:27
【问题描述】:
我正在为我的 DAL 使用 EF Core 2.1。这就是我的模型的样子
一个用户只能拥有一个角色:
// Role entity - kind of master
public class Role
{
public int RoleId { get; set; }
public string RoleName { get; set; }
}
// User entity - every user will have one role
public class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int RoleId { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedOn { get; set; }
public virtual Role Role { get; set; }
}
这就是我想/试图定义这两个实体之间的关系的方式:
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.UserId);
builder.Property(x => x.RoleId).IsRequired(true);
builder.Property(x => x.CreatedOn).IsRequired(true).HasDefaultValue(DateTime.Now);
// FK - throwing compile time error
builder.HasOne(x => x.Role).WithOne(y => y.RoleId);
}
如何使用 EF Fluent API 定义这种一用户一角色关系?
谢谢。
【问题讨论】:
-
WHAT 你遇到了什么错误??
-
@marc_s 错误 - 无法将类型“int”隐式转换为“ims.domain.model.User”
-
我不认为
builder.HasOne(x => x.Role).WithOne(y => y.RoleId);是必要的,因为按照惯例,您已经声明当您添加public int RoleId { get; set; }和public virtual Role Role { get; set; }属性时,您的用户实体应该只有一个角色。删除它,我确信您的应用程序会产生这种行为。
标签: c# entity-framework asp.net-core ef-core-2.1