I’m a novice, so I guess in the code I’m about to present, ther’re going to be lots of violations in terms of ‘proper code’. (be glad to get any remark..)
I have three entites:
public class Person
{
public int PersonId { get; set; }
public int AgeId { get; set; }
...//some properties
}
public class Age
{
public int AgeId { get; set;}
public int PersonsId { get; set; }
...//some properties
public virtual ICollection<AgeRange> AgeRanges {get; set;}
}
public class AgeRange
{
public string AgeRangeId { get; set; }
public string Value { get; set; }
ICollection<Age> Ages { get; set; }
}
I created a new ‘Age’ entity, set it’s properies with values, then, insert to its ‘Icollection’ some ‘AgeRange’ entities, which I pull out of DB. (they already exist)
I add the new ‘Age’ to dbContex, and when perform ‘savechanges’ I get exception:
Violation of PRIMARY KEY constraint 'PK_AgeRanges'. Cannot insert duplicate key in object 'dbo.AgeRanges'.
The statement has been terminated.
(AgeRange PK is string on purpose, as my intention is to keep them constant on a logic basis)
here’s the rest of the code:
[HttpPost]
public ActionResult AddPerson(AddPersonViewModel vm)
{
if (ModelState.IsValid)
{
Services services = new Services();
Age age = services.GetAgeEntity(vm.Ages);
db.Ages.Add(age);
db.SaveChanges(); //exception apears here.
........
}
public class Services
{
ModelContext db;
public Services()
{
db = new ModelContext();
}
public Age GetAgeEntity(string[] ages)
{
Age age = new Age();
//some more code...
age.AgeRanges = GetAgeRanges(ages);
return age;
}
}
ICollection<AgeRange> GetAgeRanges(string[] ages)
{
Age age = new Age();
age.AgeRanges = new List<AgeRange>();
foreach (string item in ages)
{
var ageRange = db.AgeRanges.Find(item);
age.AgeRanges.Add(ageRange);
}
return age.AgeRanges;
}
Any help will be appreciated.
You are having this error because you are using two different contexts: One the read the
AgeRangeentities from the database: It’s theModelContext dbprivate member in yourServicesclass which you create in the constructor:And a second context to add the
Ageentity together with theAgeRangecollection you are using in the controller action:This cannot be the same
dbinstance. The second context does not know anything about theAgeRangeentities because they have been loaded in another context. HenceSaveChangestries to insert them as new entities.You could create two additional methods in your
Servicesclass:And in your controller:
Now the whole operation uses the same context and your code should work.