With the Entity Framework (EF) I want to load an object from my database, modify it and save it back. However, loading and saving happens in different contexts and I modify it by adding another object to a collection property of the object.
Consider the following code based on the famous blog/posts example from MSDN:
Blog blog;
using (BloggingContext db = new BloggingContext())
{
blog = db.Blogs.Include("Posts").Single();
}
// No one else knows the `post` object directly.
{
Post post = new Post {Blog = blog, Title = "Title", Content = "Content"};
blog.Posts.Add(post);
}
using (BloggingContext db = new BloggingContext())
{
// No idea what I have to do before saving...
// Can't do anything with `post` here, since this part will not know this
// object directly.
//db.Blogs.Attach(blog); // throws an InvalidOperationException
db.SaveChanges();
}
In my database I have 1 Blog object with 100 Posts. As you can see, I want to add a new Post to this Blog. Unfortunately, doing db.Blogs.Attach(blog); before saving, throws an InvalidOperationException saying: "A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship."
What do I have to do to let the EF update this blog?
UPDATE:
I think what I was trying to achieve (decoupling the database update of an entity from the modifications and its related child entities) is not possible. Instead, I consider the opposite direction more feasible now: decoupling the update/creation of a child entity from its parent entity. This can be done the following way:
Blog blog;
using (BloggingContext db = new BloggingContext())
{
blog = db.Blogs.Single();
}
Post post = new Post {BlogId = blog.BlogId, Title = "Title", Content = "..."};
using (BloggingContext db = new BloggingContext())
{
db.Posts.Add(post);
db.SaveChanges();
}
