Home >Backend Development >C++ >ASP.NET MVC: How to Solve 'Attaching an Entity Failed' Errors Due to Duplicate Primary Keys?
Solve the "additional entity" error caused by the main key conflict in ASP.NET MVC
In ASP.NET MVC, when the editing model is updated to "modified", an error may be encountered: "The entity with the additional type of 'Modelname' failed The same primary key value ". This error occurred when the entity to be updated exists in the tracking registry that exists in the context.
In the given scenario, the error is thrown out in the following travel:
Error analysis:
<code class="language-csharp">db.Entry(aViewModel.a).State = EntityState.Modified;</code>
The problem comes from the Edit (GET)
operation of the controller, which loads the entity to be edited. In this operation,Methods try to verify user access by independent loading entities. Since then, the entity is placed in the separation state. Solution:
In order to solve the conflict, theCanuseraccessa Method must be modified to ensure that the entity is not tracked in the context of query. This can be achieved by calling the method, as shown below:
Explanation:
.AsNoTracking()
By using , the entity will not be tracked by context when loading. This prevents subsequent updates from conflicting with the state of separation.
<code class="language-csharp">private bool canUserAccessA(int aID) { int userID = WebSecurity.GetUserId(User.Identity.Name); int aFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count(); return (aFound > 0); //如果 aFound > 0,则返回 true,否则返回 false。 }</code>Conclusion:
Error "The entity failure of the additional type is 'Modelname' ..." may occur when the entity to be updated has been tracked by the context. In order to resolve this conflict, it is necessary to ensure that any independent loading entity is disabled and tracking, such as the modified
Canuseraccessa method. .AsNoTracking()
The above is the detailed content of ASP.NET MVC: How to Solve 'Attaching an Entity Failed' Errors Due to Duplicate Primary Keys?. For more information, please follow other related articles on the PHP Chinese website!