0

"Student" has a navigation property "School".

public class Student
{
    public long Id;
    public string Name;

    public School MySchool;
}
public class School
{
    public long Id;
    public string Name;
}

Client program passes in two Student entities of the same school to update database. Student.MySchool in the two Students are different objects with the same key School.Id.

How can I update the two Students in one transaction?

My thought was to attach the two Students to dbcontext then change their state to Modified. But the 2nd attaching failed with error: Attaching an entity of type 'School' failed because another entity of the same type already has the same primary key value.

sz9
  • 33
  • 6
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:28

1 Answers1

0

Add a MySchoolId property to Student and set MySchoolId property of each student based on the MySchool reference, and then set the MySchool reference to null before adding the students to the context.

public long MySchoolId { get; set; }

You may need to check and see if the School already exists in the context. If it doesn't then add it to the context, save the context, and use the freshly updated Id of that one school entity to set the value of the MySchoolId property.

Alternatively you could query the context for a match School and set each students property to the entity that came from the context or you just created.

Jeremy Cook
  • 20,840
  • 9
  • 71
  • 77
  • Thank you! My thought was to find a way without modifying the business object, for example, attach Students without attaching School. While I guess it is not possible in EF. So accept this answer. – sz9 Apr 28 '14 at 13:40
  • EF's entity state management can take some getting used to, but once understood I find that it generally makes sense...even if it isn't always convenient. – Jeremy Cook Apr 28 '14 at 19:52