Updating a belongs to with Entity Framework
Very new to EF (coming from Rails Active Record), I have some entities like so (pseudo code):
class Post
int Id
int CategoryId // Foreign Key
Category Category
string Title
class Category
int Id
string Name
In this scenario the categories are fixed, and should not be able to be edited through the Post, only assigned.
I'm exposing an API, so lets say for example we receive a HTTP PUT to a particular Post.
<Post>
<Id>1</Id>
<Category>
<Id>5</Id>
<Name>General</Name>
</Category>
<Title>Edited Title</Title>
</Post>
At this point I'm loading the Post from EF, and using AutoMapper to map a View Model representing the XML into it, then saving. The ViewModel doesn't expose the CategoryId foreign key.
When saving the post I'm running into a range of problems including new categories being created, existing categories being edited and the following error:
"The property 'Id' is part of the object's key information and cannot be modified."
I think I'm probably missing some basic principle here but I'm not sure what. Any guidance appreciated.
Update:
Ok I've extracted everything through the various layers to simplify it directly in the controller action, as follows:
public HttpResponseMessage Put(int id, [FromBody]PostViewModel viewModel)
{
Post post = Context.Posts.SingleOrDefault(p => p.Id == id);
// Merge the view model with the entity to update it
Mapper.Map<PostViewModel, Post>(viewModel, post);
Context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, Mapper.Map<Post, PostViewModel>(post));
}
Putting a breakpoint on the save line, I can see the correct nested category and category id on the entity, but its creating a new category on save.
Update:
Setting the EntityState of the Category to Detached seems to do what I want, the Category on the Post is changed (as its setting the FK) and it doesn't edit existing categories or add new ones via the "nested" model. Is that the correct way to handle this?
链接地址: http://www.djcxy.com/p/33488.html上一篇: 插入与多对多关系的记录
下一篇: 使用实体框架更新属于