在 Entity Framework 4.1 (CodeFirst) 中更新对子对象的引用
我正在尝试更新我之前使用 EntityFramework 4.1 (CodeFirst) 保存的对象
,Job 类具有以下属性...
public class Job
{
[key]
public int Id { get; set; }
public string Title { get; set; }
public Project Project { get; set; }
public JobType JobType { get; set; }
public string Description { get; set; }
}
初始创建工作正常,但更新仅提交对字符串的更改..
如果我更改子对象,例如从 JobTypeA
到 JobTypeB
的 JobType
属性 - 更改未提交...
我不想提交更改JobType - 仅针对 Job。
using (var context = new JobContext())
{
context.Jobs.Attach(job);
context.Entry(job).State = EntityState.Modified;
context.SaveChanges();
}
看一下 SQL Profiler - Id 甚至没有被发送用于更新 - 但它们是用于初始插入的!
I'm trying to update an object that I have previously saved with EntityFramework 4.1 (CodeFirst)
The class Job has the following properties ...
public class Job
{
[key]
public int Id { get; set; }
public string Title { get; set; }
public Project Project { get; set; }
public JobType JobType { get; set; }
public string Description { get; set; }
}
The initial create works fine, but the update only commits changes to the strings..
If I change the child objects eg the JobType
Property from JobTypeA
to JobTypeB
- the change is not committed ...
I'm not looking to commit a change to JobType - only to Job.
using (var context = new JobContext())
{
context.Jobs.Attach(job);
context.Entry(job).State = EntityState.Modified;
context.SaveChanges();
}
Having a look at SQL Profiler - the Ids are not even being sent for the Update - however they are for the initial insert!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将状态设置为
Modified
仅更新标量和复杂属性,而不更新导航属性。这仅通过实体框架的更改检测。这意味着您需要从数据库加载原始文件:您可能还可以在您的情况下利用一些“技巧”:
但如果您想将
JobType
设置为null ,它就不起作用
。这是一种典型的情况,如果您将外键公开为模型中的属性,情况会变得更加简单:在
Job
实体中使用JobTypeId
,您的代码将可以工作,因为 FK 属性是标量,将状态设置为Modified
也会将此属性标记为已修改。Setting the state to
Modified
only updates scalar and complex properties, not your navigation properties. This only goes through Entity Framework's change detection. It means that you need to load the original from the database:You could probably also leverage some "tricks" in your case:
It wouldn't work though if you want to set
JobType
tonull
.This is a typical situation which is getting much simpler if you expose foreign keys as properties in your model: With a
JobTypeId
in yourJob
entity your code would work because the FK property is scalar and setting the state toModified
will also mark this property as modified.