EF-6 Avoid duplicating existing property

Viewed 62

Suppose you have an Entity Animal that has a property of AnimalType Entity (linked by FK in the database).

There are fixed AnimalTypes already stored in the database (mammal/reptile/fish).

When a new Animal is created, the property AnimalType is populated with one of the values above (pulled from the DB).

So the Animal doesn't exist in the DB yet, but the AnimalType does. Using EF 6, I want to save the newly created Animal in the database.

But I run into problems when adding the Animal:

db.Animals.Add(animal);

This doesn't throw any errors, but it creates duplicates in the AnimalType table (so if type was mammal, there will be duplicated mammal records).

I tried to stop it preventing duplicates by attaching the Animal Type first:

db.AnimalTypes.Attach(animal.AnimalType);

But this throws an error:

Attaching an entity of type 'AnimalType' failed because another entity of the same type already has the same primary key value. 

How can I tell EF that the Animal is new and needs adding, but the AnimalType property already exists in the DB (and should just link via foreign key)?

0 Answers
Related