[英]Using Entity Framework 4.1, how can I achive below requirement?
Consider I have 2 entities - a) Publisher b) Book Publisher has navigation property called as PublishedBooks which is collection of Books. 考虑我有2个实体-a)出版商b)图书出版商具有称为PublisherBooks的导航属性,它是Books的集合。 Assume that Publisher1 has published 2 books ie Book1 & Book2 What I would like to do is, for a Publisher1, delete published book Book1 and add a new published book (ie Book3), in the database. 假设Publisher1已出版了2本书,即Book1和Book2,我想为Publisher1删除数据库中已出版的书Book1并添加新的已出版的书(即Book3)。
Context.SaveChanges() throwing below error - Context.SaveChanges()抛出以下错误-
The operation failed: 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. 如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
Note : Delete cascade rule is present in database as well as in the context class. 注意:数据库以及上下文类中都存在删除级联规则。 BTW, I am using C# & Sql Server 2005. 顺便说一句,我正在使用C#和Sql Server 2005。
Sounds like you are doing something like this: 听起来您正在执行以下操作:
Foo foo = entity.RelatedFoos.Where(f=>f.id=xyz);
entity.RelatedFoos.Remove(foo); //this is the problematic line
context.SaveChanges();
That is; 那是; you are removing an entity from a set of related items - not from the main collection on the context itself. 您是从一组相关项中删除一个实体-而不是从上下文本身的主集合中删除。 As noted in the error, removing the above way only removes the relation . 如错误中所指出的,删除上述方法只会删除关系 。 Not the object foo
. 不是对象foo
。 This is probably what you meant, if you mean to delete the foo
: 如果要删除foo
,可能就是您的意思了:
Foo foo = entity.RelatedFoos.Where(f=>f.id=xyz);
context.Foos.Remove(foo);
context.SaveChanges();
You need to explicitly delete the child object before the save, eg 您需要在保存之前显式删除子对象,例如
Context.DeleteObject(Book1);
Context.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.