Entity Framework Optional: Optional Link

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.

+7
source share
1 answer

It looks like you're trying to set up a 1: 0..1 ratio from your AdditionalType objects (which I may have misinterpreted.

NB I think you would need to use a BaseTableId for your BaseTable for this to work (or define a primary key):

If BaseTableId is a foreign key in this instance, I think this might be what you need:

 modelBuilder.Entity<AdditionalType1>() .HasOptional(zmt => zmt.BaseTable) .WithMany() .HasForeignKey(a => a.BaseTableId); 

This is what I used earlier, but I can not admit to its full understanding (.WithMany () disables me); this is a small workaround indicated in the article from this answer: Entity ratio from 0.1 to 0)

Sorry if I completely missed the point.

+5
source

All Articles