实体框架:'ComplexType.Field'属性不存在或未映射到类型'Entity'
本文关键字:映射 Entity 类型 Field 框架 ComplexType 实体 属性 不存在 | 更新日期: 2023-09-27 18:11:50
我有一个映射属性值对象/复杂类型到实体的问题。我有一个用户实体,它有一个名为Credential的复杂类型属性,它又有属性:Email、UserName、Password和SecurityStamp。我试图将属性从复杂类型映射到实体,源代码如下所示:
public class User
{
public string Id { get; protected set; }
public Credential Credential { get; protected set; }
// unrelated properties and methods omitted for simplicity
}
public sealed class Credential: ValueObject<Credential>
{
public string Email { get; private set; }
public string UserName { get; private set; }
public string Password { get; private set; }
public string SecurityStamp { get; private set; }
public Credential() { }
public Credential(string email, string userName, string password, string securityStamp)
{
Email = email;
UserName = userName;
Password = password;
SecurityStamp = securityStamp;
}
public class CoreContext: DbContext
{
public IDbSet<User> Users { get; set; }
public CoreContext(string connectionString) : base(connectionString) {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<CoreContext>(null);
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.Email).HasColumnName("Email");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.UserName).HasColumnName("UserName");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.Password).HasColumnName("Password");
modelBuilder.ComplexType<Credential>().Property(ucr => ucr.SecurityStamp).HasColumnName("SecurityStamp");
modelBuilder.Entity<User>().Property(u => u.Credential.Email).HasColumnName("Email");
modelBuilder.Entity<User>().Property(u => u.Credential.UserName).HasColumnName("UserName");
modelBuilder.Entity<User>().Property(u => u.Credential.Password).HasColumnName("Password");
modelBuilder.Entity<User>().Property(u => u.Credential.SecurityStamp).HasColumnName("SecurityStamp");
}
}
如您所见,我试图将复杂类型属性映射到实体。我首先将Credential配置为复杂类型,然后在实体User上配置属性。然而,我收到以下错误:
The 'Credential.Email' property does not exist or is not mapped for the type 'User'.
我不明白为什么会这样。我已经做了一切,我可以配置复杂的类型映射,为什么它不工作?有人知道我哪里做错了吗?
无法复制此:
我在使用相同的设置添加迁移后得到了这个:
public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(),
UserName = c.String(),
Password = c.String(),
SecurityStamp = c.String()
})
.PrimaryKey(t => t.Id);
}
我已经删除的唯一的东西是你的基类上凭据:ValueObject,因为我没有它。一切看起来都很好,也许这门课有什么问题?