I think I am missing something simple here. I am getting the error:
“Violation of PRIMARY KEY constraint ‘PK_FeatureTypes’. Cannot insert duplicate key in object ‘dbo.FeatureTypeCodes’. The duplicate key value is (28).\r\nThe statement has been terminated”
I have a look-up / linked table of FeatureType – (Mountain, Lake, River, etc.) which is already populated with data and is defined as:
[Table("FeatureTypeCodes")]
public class FeatureTypeCode {
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int FeatureTypeCodeID { get; set; }
public string Name { get; set; }
}
This is linked to my place table / object like this:
[Table("Places")]
public class Place {
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int PlaceID { get; set; }
public string Name { get; set; }
public FeatureTypeCode FeatureTypeCode { get; set; }
public ICollection<PlaceCoordinate> PlaceCoordinates { get; set; }
}
Then I am loading them from the old database like this (it is part of my conversion code):
foreach (DataRow r in table.Rows) {
int ftID = Convert.ToInt32(r["FeatureTypeId"]);
Place temp = new Place {
PlaceID = Convert.ToInt32(r["PlaceID"]),
Name = r["PlaceName"].ToString(),
FeatureTypeCode = featureTypeCodeRepository.FeatureTypeCodes.FirstOrDefault(o=>o.FeatureTypeCodeID == ftID)
};
places.Add(temp);
}
The error is being generated when it tries to insert a new FeatureType object with the same ID as an existing object while saving a Place. My thought was that by loading FeatureType from the context it would not attempt to insert a new FeatureType on saving the Place object. I am obviously wrong on that, but is it something simple I am missing?
I don’t think that you use the same DBContext Object in your
featureTypeCodeRepositoryand theplaces.Add(temp);. So I think that basically EF don’t keep track of the FeatureTypeCodes becuse it’s loaded by one context, and saved by another.