Skip to content
Advertisement

Problem with foreign key in Entity Framework one to many

I am having some foreign key problems, it turns out that I am doing a revision to an old system in which a new table is added, and in doing so, the following arises.

In short, I have the following 3 classes.

The issue is that both StepUp and Transformador have a 1- * relationship with Accessorio_x_Trafos.

When migrating, the database is created correctly (FKs are added)

enter image description here

(Ignore the FK Accesorios which is one of the properties that I removed so as not to have so much code)

The issue is that when I try, both modify an object of type Transformer (I do it as follows)

But this throws the follow exception

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while…

And in the InnerException the

Instrucción INSERT en conflicto con la restricción FOREIGN KEY “FK_dbo.Accesorio_x_Trafos_dbo.StepUps_CodigoDelfos_Revision”. El conflicto ha aparecido en la base de datos “DBTrafos”, tabla “dbo.StepUps”.rnSe terminó la instrucción.

How can i deal with this?

Advertisement

Answer

I solve my issue by creating an abstract class that replaced Accessory_x_Trafos in such a way, that you then specify each inherited class with its foreign key and corresponding navigation property.

In this way, in each of the corresponding classes, I used properties, either type ICollection<AccesorioStepUp> or type ICollection<AccesorioDistribucion>.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement