entity framework Add Entity adds child entities as well
I have a table "Training" that has a column "CreatedBy" which has a referential integrity to the "User" table. So "CreatedBy" is actually a "User" representing the user who inserted the training record.
Now when I add a new "Training" entity, it's "CreatedBy" is an old "User". So it should not try to add the user as well. But it does and so fails because it violates the unique key constraint.
Here's the code. Where am I going wrong?
public int AddEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Trainings.AddObject(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}
public int UpdateEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Trainings.ApplyCurrentValues(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}
public int Save(Training entity, bool isSavedInstantly)
{
IEnumerable<Training> training = this.trainersDeskDBModel.Trainings.Where(x => x.Id == entity.Id);
if (training开发者_开发问答 != null && training.Count() > 0)
{
this.UpdateEntity(entity, isSavedInstantly);
}
else
{
this.AddEntity(entity, isSavedInstantly);
}
return entity.Id;
}
If you didn't load the User
in the same context where you are adding the new Training
in you must EF tell that the User
already exists in the DB by attaching it to the context before you add the new Training
:
public int AddEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Users.Attach(entity.CreatedBy);
this.trainersDeskDBModel.Trainings.AddObject(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}
精彩评论