我正在使用Entity Framework 4.3.1 Code-First,我需要在两个表之间拆分一个实体.这些表具有共享的主键,它是1对1,但是每个表上的列的名称不相同.
我不控制数据布局,也不能请求任何更改.
所以例如,sql表可能是
这将是我的实体…
public class MyEntity { public int Id {get; set;} public string Name {get;set} public string FromAnotherTable {get;set;} }
这里是我的映射.
public class MyEntityMapping : EntityTypeConfiguration<MyEntity> { public MyEntityMapping() { this.Property(e => e.Id).HasColumnName("ThePrimaryKeyId"); this.Property(e => e.Name).HasColumnName("MyDatabaseName"); this.Property(e => e.FromAnothertable).HasColumnName("AnotherTableColumn"); this.Map(m => { m.Properties(e => { e.Id,e.Name }); m.ToTable("MainTable"); }); this.Map(m => { m.Properties(e => { e.Id,e.FromAnotherTable }); m.ToTable("ExtendedTable"); }); }
由于他们之间共享的密钥有不同的列名,我不知道如何映射它.该映射将编译,但在运行时失败,因为EF发出sql查找“ExtendedTable”表上不存在的“ThePrimaryKeyId”列.
编辑
要澄清一点,如果PK上的“ExtendedTable”遵循命名规则,上面所定义的(并且可以)工作.但是它不是,我不能改变模式.
基本上,我需要的EF要发出的是一个sql语句
SELECT [e1].*,/*yes,wildcards are bad. doing it here for brevity*/ [e2].* FROM [MainTable] AS [e1] INNER JOIN [ExtendedTable] AS [e2] /*Could be left join,don't care. */ ON [e1].[ThePrimaryKeyId] = [e2].[NotTheSameName]
但是,似乎想排放的唯一的东西是
SELECT [e1].*,[e2].* FROM [MainTable] AS [e1] INNER JOIN [ExtendedTable] AS [e2] ON [e1].[ThePrimaryKeyId] = [e2].[ThePrimaryKeyId] /* this column doesn't exist */
编辑
我在NSGaga的建议下再次尝试了一对一的做法.它没有工作,但这里是结果.
实体
public class MyEntity { public int Id { get; set; } public int Name { get; set; } public virtual ExtEntity ExtendedProperties { get; set; } } public class ExtEntity { public int Id { get; set; } public string AnotherTableColumn { get; set; } public virtual MyEntity MainEntry { get; set; } }
以下是映射类
public class MyEntityMapping : EntityTypeConfiguration<MyEntity> { public MyEntityMapping() { this.Property(e => e.Id).HasColumnName("ThePrimaryKeyId"); this.Property(e => e.Name).HasColumnName("MyDatabaseName"); this.ToTable("MainTable"); this.HasKey(e => e.Id); this.Hasrequired(e => e.ExtendedProperties).WithrequiredPrincipal(f => f.MainEntry); } } public class ExtEntityMapping : EntityTypeConfiguration<ExtEntity> { public ExtEntityMapping() { this.Property(e => e.Id).HasColumnName("NotTheSameName"); this.Property(e => e.AnotherTableColumn).HasColumnName("AnotherTableColumn"); this.ToTable("ExtendedTable"); this.HasKey(e => e.Id); this.Hasrequired(e => e.MainEntry).WithrequiredDependent(f => f.ExtendedProperties); } }
此设置将获取消息
"Column or attribute 'MyEntity_ThePrimaryKeyId' is not defined in 'ExtendedTable'"
将最终的地图行更改为
this.Hasrequired(e => e.MainEntry).WithrequiredDependent(f => f.ExtendedProperties).Map(m => M.MapKey("NotTheSameName"));
返回此消息
"Each property name in a type must be unique. property name 'NotTheSameName' was already defined."
更改映射键以使用父表MapKey(“ThePrimaryKeyId”)中的列.返回此消息
"Column or attribute 'ThePrimaryKeyId' is not defined in 'ExtendedTable'"
@R_404_323@
我找不到任何具体说明列的名称在两个表中必须相同的任何东西;但是我也不能找到任何不说的内容,也不能解释如何映射这种情况.我可以找到的每个例子都有两个表中相同名字的键.它看起来像是DbContext设计中的一个洞.