R – Entity framework and foreign keys

entityentity-frameworkforeign-keys

I have two tables, a car table which contains different properties for a car, and a carmodeldefinition which is a foreign key to a table with the same name. The cardefinition table contains the different cars and models. I have mapped them in the entity framework.

image

When I try to add a new car within carmodeldefinition it simply adds a new cardefinition instead of just using the one it finds. The code for it can be found below:

   DataLayer.Car car = new DataLayer.Car();
   car.URL = carBulk.URL;
   car.SellerCity = carBulk.SellerCity.ToString();
   car.Color = carBulk.Color.ToString();
   car.SellerStreet = carBulk.SellerStreet;
   car.SellerName = carBulk.SellerName;
   car.SellerCountry = carBulk.SellerCountry.ToString();
   if (cdDTO != null && cdDTO.CarDefinitionId > 0)
   {
       car.CarModelDefinition = cdDTO.Transform(cdDTO);
   }

   mee.AddToCar(car);
   mee.SaveChanges();

The cdDTO.Transform(cdDTO) transforms the datatransferobject to an object that can be mapped to the database. The weird thing it that cdDTO.Transform(cdDTO); returns the correct object with the correct cardefintionId, but when it is inserted, it is just inserted in the bottom with a new cardefinitionid (which is the pk).

Best Solution

I found the answer. As studpid as I were, I set the relation to 1-1 instead of 1-many.