Look at this code:
Blog blog = new Blog { Url = "http://blogs.msdn.com/adonet" };
blog.Posts.Add(
new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
db.Add(blog);
db.SaveChanges();
// db.Database.ExecuteSqlRaw("Delete from Blogs"); --> throw exception for Foreign key
//db.Remove(blog); // --> works and doesn't throw exception
db.SaveChanges();
I don't understand why when deleting a blog who contain a post, we have an exception for foreign key (it is normal because I removed the cascade option). But when I do db.Remove(blog), no exception is thrown, and the blog is deleted from the database...
CodePudding user response:
you have to add Id to your sql script. As it is now you are deleting all blogs, not just a new one. But some posts can have BlogId from another posts and you can not delete them, before you assign a foreign key to null or if it is not possible delete all the posts before.
db.Database.ExecuteSqlRaw("Delete from Blogs where BlogId=" blog.BlogId.ToString());
CodePudding user response:
Have a read of https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.deletebehavior?view=efcore-5.0
There are various ways you can tell EF to behave when you remove a parent entity. If you're not seeing the database throw an error when you remove a parent then EF is doing some fix up in the background - either successfully deleting all the children it knows about first, or breaking the relationship by setting the foreign key column of the child to null (orphaning) first, before removing the parent
If you've never specifically set any behavior then what EF is doing will depend on whether Post.BlogId is nullable or not. If it's not, then the posts will be being deleted. If it is then they'll be being set to have a null BlogId.
You can show the SQLs being executed (always a handy debug tool) if you find the UseSqlServer call in your startup config and chain something like a call to .LogTo(Console.WriteLine, LogLevel.Information) onto it
