我为必须映射到同一数据库表的两个实体创建映射而陷入困境。我需要它的原因是创建将在不同情况下使用的精简实体和完整实体。我已经有现有的数据库,并且我有一个自己的数据库上下文,该上下文是从DbContext
类派生的。所有映射都是通过使用EntityTypeConfiguration<T>
类进行的。
桌子。
[PROCESS]
ProcessId <int> PK
Name <nvarchar>
StartDate <datetime>
ProcessSequency <int>
Limit <int>
OwnerName <nvarchar>
现在该表已映射到单域模型,但是我想更改它。 我想将此实体拆分为下两个实体。
public class ProcessEntity
{
public int ProcessId { get; set; }
public int Name { get; set; }
public virtual ProcessDetailsEntity ProcessDetails { get; set; }
}
public class ProcessDetailsEntity
{
public int ProcessId { get; set; }
public DateTime StartDate { get; set; }
public int ProcessSequency { get; set; }
public int Limit { get; set; }
public string OwnerName { get; set; }
public virtual ProcessEntity ProcessBase { get;set; }
}
我为它们创建了两个配置类。
public class ProcessEntityConfiguration : EntityTypeConfiguration<ProcessEntity>
{
public ProcessEntityConfiguration()
{
// ToTable("PROCESS");
Map(m => m.ToTable("PROCESS"))
HasKey(t => t.ProcessId);
HasRequired(s => s.ProcessDetails).WithRequiredPrincipal(t => t.ProcessBase);
}
}
public class ProcessDetailsEntityConfiguration : EntityTypeConfiguration<ProcessDetailsEntity>
{
public ProcessDetailsEntityConfiguration()
{
// ToTable("PROCESS");
HasKey(t => t.ProcessId);
Map(m => m.ToTable("PROCESS"));
}
}
一切看起来都不错,应该可以,但是我看到了错误:
“ InnerException”:{ “ Message”:“发生错误。”, “ ExceptionMessage”:“无效的列名'Discriminator'。\ r \ n无效的列名'Discriminator'。”, “ ExceptionType”:“ System.Data.SqlClient.SqlException”, “ StackTrace”:“位于System.Data.SqlClient.SqlConnection.OnError(SqlException异常, 布尔值breakConnection,动作为1 wrapCloseInAction)
我在Google上进行了搜索,发现Discriminator
被实体框架用来实施TPH - Table per hierarchy的行为。我还发现了一篇有用的文章,可能对我来说是解决方案:Entity Framework - Advanced mapping scenarios。不幸的是,将单个表映射到多个实体标题下提供的解决方案对我不起作用,我也不知道为什么。您能帮我解决这个问题吗?
我对NHibernate
有点熟悉,所以我尝试以NHibernate
的方式来做。这个想法是创建两个独立的实体。这是我的第一个方法。这是此尝试的代码。
public abstract class ProcessBaseEntity
{
public int ProcessId { get; set; }
public int Name { get; set; }
}
public class ProcessEntity : ProcessBaseEntity
{
}
public class ProcessDetailsEntity : ProcessBaseEntity
{
public DateTime StartDate { get; set; }
public int ProcessSequency { get; set; }
public int Limit { get; set; }
public string OwnerName { get; set; }
}
public class ProcessEntityConfiguration : EntityTypeConfiguration<ProcessEntity>
{
public ProcessEntityConfiguration()
{
ToTable("PROCESS");
HasKey(t => t.ProcessId);
}
}
public class ProcessDetailsEntityConfiguration : EntityTypeConfiguration<ProcessDetailsEntity>
{
public ProcessDetailsEntityConfiguration()
{
ToTable("PROCESS");
HasKey(t => t.ProcessId);
}
}
很遗憾,此尝试未成功。引发了以下异常:
实体类型“ ProcessEntity”和“ ProcessDetailsEntity”不能 共享表“ PROCESS”,因为它们不在同一类型层次结构中 或与之没有有效的一对一外键关系 它们之间匹配主键。
我开始将我的第一个实体分成两个小实体,因为我想使我的SQL查询尽可能轻。有时我想知道是否必要?甚至我随口吐痰,我的要求也不会减轻。也许值得将我的所有财产都放在一个实体中,而不必理会。