user7247317
user7247317

Reputation:

ASP.NET - DbUpdateException : DELETE statement conflicted with the REFERENCE constraint

I have a Post model, with a virtual ICollection of type AspNetIdentityUser.

public class Post{
   public int Id { get; set; }
   public string Title { get; set; }
   public virtual ICollection<ApplicationUser> Views  { get; set; }
}

The Post model shouldn't have any sort of relationship with ApplicationUser as the VIEWS property simply acts as a counter. I have not modified the IdentityModel.

But after adding a ApplicationUser to the collection, and when I attempt to delete the Post object I get a DbUpdateException.

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.AspNetUsers_dbo.Posts_Post_Id". The conflict occurred in database "aspnet-project-test-asp", table "dbo.AspNetUsers", column 'Post_Id'.

I'm using this code to delete the object:

Post post = db.Posts.Find(id);
db.Posts.Remove(post);
db.SaveChanges();
return RedirectToAction("Index");

Upvotes: 1

Views: 1789

Answers (1)

Manprit Singh Sahota
Manprit Singh Sahota

Reputation: 1339

This is because you have Application Users having Post Id as foriegn key. You must first remove the users having reference to Post then delete the Post.

Post post = db.Posts.Find(id);
db.User.RemoveRange(post.Views);
db.Posts.Remove(post);
db.SaveChanges();
return RedirectToAction("Index");

Alternatively, you should set the PostId of the users to Null and then delete the Post. I think User is a separate entity and it must not have reference to PostId. Can you show you Application User class also?

Also, it will be great if you can paste screenshot of records for both the tables.

Moving further you should add below code to the constructor of your DbContext class which will help you to review the actual query executed by entity framework in output window.

Database.Log = s => Trace.WriteLine(s);

Upvotes: 2

Related Questions