开发者

Entity Framework Insert, Update, Delete During Same Transaction

开发者 https://www.devze.com 2023-03-14 21:22 出处:网络
I have a problem, I have a wizard that can update data AND insert data. So, if I have an existing list of team members, I can update their roles but If necessary, I can开发者_高级运维 also add/insert

I have a problem, I have a wizard that can update data AND insert data. So, if I have an existing list of team members, I can update their roles but If necessary, I can开发者_高级运维 also add/insert a person to this team. So I can update roles and insert a new team member into the same table all during the same transaction. Data can be updated to and inserted to table teamMembers.

When I try to add a new teamMember, I also have an existing member where I simply want to update his role. Both changes happen to the same table called TeamMember. When I debug the context, everything looks good. it shows that there are two changes that will occur for the TeamMember table. One transaction is the update and the other transaction is the insert. When I perform an update using:

var teamMember = new TeamMember
{
    Name = user.FullName,
    UserProfileId = user.UserProfileId,
    RoleId = user.RoleId
};

TeamMemberList.Add(teamMember);
project.TeamMembers = TeamMemberList;

//And then call 
this.Context.Projects.Attach(project);
this.Context.Entry(project).State = System.Data.EntityState.Modified;

it updates but the record that needs to be inserted fails.

HOW CAN I DO BOTH AN INSERT AND UPDATE TO THE SAME TABLE DURING THE SAME TRANSACTION?

CURRENT ERROR IS:

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.


I think you need to add the TeamMember entity to the context's global list. Something like:

var teamMember = new TeamMember()
{
  Name = user.FullName,
  UserProfileId = user.UserProfileId,
  RoleId = user.RoleId
}

project.TeamMembers.Add( teamMember );
this.Context.TeamMembers.Add( teamMember );

this.Context.SaveChanges();


How about loading the existing project entity first and then adding members.

var project = this.Context.Project.Where(p => p.ID = "bar").Include("TeamMembers").FirstOrDefault();

var teamMember= new TeamMember
{
    Name = user.FullName,
    UserProfileId = user.UserProfileId,
    RoleId = user.RoleId
};

project.TeamMembers.Add(teamMember);

this.Context.SaveChanges()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号