I am trying to customize an Entity Framework model with an optional: optional relationship:
In my situation, sometimes an AdditionalData record exists that points to a BaseTable record, but sometimes a BaseTable or AdditionalData record exists without any connection. The foreign key to BaseTable (if it exists) is in the table of additional data.
I want to be able to navigate between BaseTable and any additional data that can be connected.
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; } }
How do I do this job? I got to:
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"));
but he tells me the following:
error: (1564,6): error 0019: each property name in the type must be unique. The name of the BaseTableId property is already defined.
I do not know exactly what this means, and I'm not sure how to fix it.
EDIT: If I remove the Map / MapKey clauses as suggested here ( https://stackoverflow.com/a/167269/ ), I get this error instead when a query that uses it is executed:
Invalid column name 'BaseTable_Id' because it automatically maps to BaseTable_Id instead of my BaseTableId field.
Scott stafford
source share