我正在尝试使用可选的:可选关系来设置实体框架模型:
在我的情况下,有时存在指向BaseTable记录的AdditionalData记录,但有时BaseTable或AdditionalData记录存在而没有任何链接. BaseTable的外键(如果存在)位于AdditionalData表上.
我希望能够在BaseTable和可能连接的任何AdditionalDatas之间来回导航.
BaseTable 0..1 ----- 0..1 AdditionalData1 \ --- 0..1 AdditionalData2
public class BaseTable { public int Id { get; set; } public virtual AdditionalType1 AdditionalType1 { get; set; } public virtual AdditionalType2 AdditionalType2 { get; set; } } public class AdditionalType1 { public int Id { get; set; } public int? BaseTableId { get; set; } public virtual BaseTable BaseTable { get; set; } } public class AdditionalType2 { public int Id { get; set; } public int? BaseTableId { get; set; } public virtual BaseTable BaseTable { get; set; } }
我该如何工作?我得到了:
modelBuilder.Entity<AdditionalType1>() .HasOptional(zmt => zmt.BaseTable) .WithOptionalDependent(zm => zm.AdditionalType1) .Map(a => a.MapKey("BaseTableId")); modelBuilder.Entity<AdditionalType2>() .HasOptional(zmt => zmt.BaseTable) .WithOptionalDependent(zm => zm.AdditionalType2) .Map(a => a.MapKey("BaseTableId"));
但它告诉我这个:
error: (1564,6) : error 0019: Each property name in a type must be
unique. Property name ‘BaseTableId’ was already defined.
我不知道究竟是什么意思,也不确定如何修复.
编辑:如果我删除这里建议的Map / MapKey子句(https://stackoverflow.com/a/8016308/237091)我得到此错误,当一个查询运行使用它时:
Invalid column name ‘BaseTable_Id’
as it maps itself to BaseTable_Id automatically instead of my BaseTableId field.
解决方法
看起来你正在尝试从AdditionalType对象设置1:0..1关系(我可能完全误解了).
注:我认为您必须在BaseTable上持有BaseTableId才能使其工作(或定义主键):
如果BaseTableId是这个实例中的外键,我想这可能就是你所追求的:
modelBuilder.Entity<AdditionalType1>() .HasOptional(zmt => zmt.BaseTable) .WithMany() .HasForeignKey(a => a.BaseTableId);
这是我之前使用过的,但不能承认完全理解它(.WithMany()让我兴奋);这个答案的文章中列出了一个小的解决方法:Entity Framework 0..1 to 0 relation)
如果我完全错过了这一点,我会道歉.