我正在尝试使用Entity Framework 5 Code First实现状态模式。
我的场景有一个名为LotStatus的抽象部分基类和5个继承自此类的类:OpenStatus,AwardedStatus,CancelledStatus,ContractSignedStatus和EvaluationStatus:
public abstract partial class LotStatus { ... }
public class OpenStatus : LotStatus { ... }
public class AwardedStatus : LotStatus { ... }
在来自DBContext的OnModelCreating中,我将一个配置添加到模型构建器以映射这些实体:
modelBuilder.Configurations.Add(new LotStatusConfiguration());
LotStatusConfiguration的代码如下:
public class LotStatusConfiguration : EntityTypeConfiguration<LotStatus>
{
public LotStatusConfiguration()
{
ToTable("LotStatus");
HasKey(ls => ls.LotStatusID);
this.Map<OpenStatus>(pk => pk.Requires("Discriminator").HasValue(typeof(OpenStatus).AssemblyQualifiedName).HasColumnType("nvarchar(max)"));
this.Map<EvaluationStatus>(pk => pk.Requires("Discriminator").HasValue(typeof(EvaluationStatus).AssemblyQualifiedName).HasColumnType("nvarchar(max)"));
this.Map<AwardedStatus>(pk => pk.Requires("Discriminator").HasValue(typeof(AwardedStatus).AssemblyQualifiedName).HasColumnType("nvarchar(max)"));
this.Map<ContractSignedStatus>(pk => pk.Requires("Discriminator").HasValue(typeof(ContractSignedStatus).AssemblyQualifiedName).HasColumnType("nvarchar(max)"));
this.Map<CancelledStatus>(pk => pk.Requires("Discriminator").HasValue(typeof(CancelledStatus).AssemblyQualifiedName).HasColumnType("nvarchar(max)"));
}
}
当EF尝试创建数据库时,会引发错误:
The type 'OpenStatus' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
我没有任何[NotMapped]标签,我在做什么?有些想法?
谢谢!
答案 0 :(得分:1)
解决!
我在此项目中定义了另一种状态模式。问题是因为在其他状态模式中实现了另一个继承自另一个抽象类(ProcedureStatus)的OpenStatus类。
Core.ProcedureAggregate.OpenStatus : ProcedureStatus
Core.LotAggregate.OpenStatus : LotStatus
我将状态名称更改为OpenLotStatus并且有效...
Core.ProcedureAggregate.OpenStatus : ProcedureStatus
Core.LotAggregate.OpenLotStatus : LotStatus
虽然它们已在不同的命名空间中定义,但看起来不可能有两个具有相同名称的类...
感谢所有人:)
答案 1 :(得分:0)
您似乎忘记在DbContext
中添加实体,例如
public DbSet<LotStatus> LotStatuses { get; set; }
,请参阅此处