Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用实体框架更新所属的_C#_Entity Framework - Fatal编程技术网

C# 使用实体框架更新所属的

C# 使用实体框架更新所属的,c#,entity-framework,C#,Entity Framework,对于来自Rails Active Record的EF来说非常新,我有一些实体,比如伪代码: class Post int Id int CategoryId // Foreign Key Category Category string Title class Category int Id string Name 在这种情况下,类别是固定的,不能通过帖子编辑,只能分配 我公开了一个API,比如说我们收到了一个针对特定Post的HTTP <Post&

对于来自Rails Active Record的EF来说非常新,我有一些实体,比如伪代码:

class Post
   int Id
   int CategoryId // Foreign Key
   Category Category
   string Title

class Category
   int Id
   string Name
在这种情况下,类别是固定的,不能通过帖子编辑,只能分配

我公开了一个API,比如说我们收到了一个针对特定Post的HTTP

<Post>
  <Id>1</Id>
  <Category>
    <Id>5</Id>
    <Name>General</Name>
  </Category>
  <Title>Edited Title</Title>
</Post>
此时,我正在从EF加载帖子,并使用AutoMapper将表示XML的视图模型映射到其中,然后保存。ViewModel不公开CategoryId外键

保存帖子时,我遇到了一系列问题,包括创建新类别、编辑现有类别以及以下错误:

属性“Id”是对象密钥信息的一部分,无法修改

我想我可能遗漏了一些基本原则,但我不确定是什么。感谢您的指导

更新:

好的,我通过各个层提取了所有内容,以便在控制器操作中直接简化,如下所示:

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));
}
将断点放在保存行上,我可以看到实体上正确的嵌套类别和类别id,但它会在保存时创建一个新类别

更新:


将类别的EntityState设置为Distached似乎是我想要的,帖子上的类别会随着设置FK而更改,它不会通过嵌套模型编辑现有类别或添加新类别。这是正确的处理方法吗?

我们还缺少一些基本的东西……保存帖子时使用的代码。@Rufus L:只是Context.SaveChanges;通过视图模型中的AutoMapper更新实体后