EF 4.1: Replacing a child entity before inserting the parent
When I try to insert an entity that had a child that I replaced by another child, I'm getting an error message.
Here are the details:
I have a one-to-many relationship where the child element sometimes needs to be inserted and other times it needs to be updated. This is concerning an ASP.Net MVC 3 project using EF 4.1.
Here is an example to illustrate what I am trying to do. Let's say I have these 2 objects:
public class Foo {
[Key]
public int FooId { get; set; }
public int BarId { get; set; }
public Bar bar { get; set; }
public string type;
}
public class Bar {
[Key]
public int BarId { get; set; }
public string name;
public string email;
}
And I have a form to create a new Foo having these 3 fiels:
- Type
- Name
Now, before saving Foo, I check whether Bar already exists in my database using the email field, since I don't want to have two Bars with the same email. If there is no Bar with the given email, everything is fine and I save Foo, which creates a new Foo and a new Bar in the the database. However, if I find an existing Bar in the database, I do the following:
existingBar.Name = myFoo.Bar.Name; //To update the name
myFoo.Bar = existingBar; //Replace the Bar that was going to be inserted with Foo by the existing one
fooRepository.Add(myFoo);
SaveFoo();
When I do this however, I get the following error message:
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 s开发者_开发知识库et 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.
I also tried this:
existingBar.Name = myFoo.Bar.Name; //To update the name
ModelCopier.CopyModel(existingBar, myFoo.Bar);
fooRepository.Add(myFoo);
SaveFoo();
In this case, I am getting the following error message:
Collection was modified; enumeration operation may not execute.
So, is there a way save myFoo with an existing Bar as child?
Have you tried calling barRepository.update(existingBar) after modifying it? THEN attempt to add your new Foo.
精彩评论