MVC 导航属性试图移除某条记录报如下错误
The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
具体如下:
定义了两个model
public class Blog { public int BlogId { get; set; } public string Name { get; set; } public string Url { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Post { public int PostID { get; set; } public int BlogId { get; set; } public string Name { get; set; } public string Url { get; set; } public virtual Blog Blog { get; set; } }
然后往这两个model对应的表中写入记录,之后再删除博客1下面的所有post,结果报了上面的错误
using (var db = new BlogContext()) { //添加数据 Blog b = new Blog { Name = "Another Blog " + db.Blogs.Count() }; Post po = new Post(); po.Name = "post" + db.Blogs.Count(); po.Url = "http://www.baidu.com"; b.Posts=new List<Post>(); b.Posts.Add(po); db.Blogs.Add(b); db.SaveChanges(); //尝试删除blog1下面的所有文章 var blog1 = db.Blogs.Find(1); for (int k = blog1.Posts.Count() - 1; k >= 0; k--) { var p = blog1.Posts.ToList()[k]; blog1.Posts.Remove(p); } db.SaveChanges(); }
经过研究发现是我理解错误blog1.Posts.Remove(p);这句代码的作用把blog1和p两个对象之间的关系断开,即把p的blogid设置为null,不是不p从数据库中删除,而我们设置了blogid 外键不能为null,这就不难理解为什么出现上面的错误了
为了使上面不报错可以把blogid设置为允许null。但是这并不是我想要的,我想要的是删除blog1下面的所有文章,要达到这个效果要直接操作post对应的表,比如
var post = db.Posts.Find(1);
db.Posts.Remove(post);
通过这个问题我也再次理解到导航属性是用来管理两个表直接的关系的,并不可以通过导航属性直接删除导航属性表的数据,虽然可以通过导航属性添加数据