更新到实体框架4.1的子对象的引用(CodeFirst) [英] Updating a reference to a child object in Entity framework 4.1 (CodeFirst)
问题描述
我试图更新,我以前保存的EntityFramework 4.1(CodeFirst)
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..
如果我改变子对象如 JobType
属性从 JobTypeA
到 JobTypeB
- 更改不会犯...
If I change the child objects eg the JobType
Property from JobTypeA
to JobTypeB
- the change is not committed ...
我不希望承诺JobType改变 - 只有到作业
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();
}
在看看SQL事件探查器 - ID是不甚至被用于发送更新 - !不过他们是初始插入
Having a look at SQL Profiler - the Ids are not even being sent for the Update - however they are for the initial insert!
推荐答案
状态设置为修改
仅更新标量和复杂性,而不是你的导航性能。这只经过实体框架的变化检测。这意味着,你需要从数据库中加载原文:
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:
using (var context = new JobContext())
{
var originalJob = context.Jobs.Include(j => j.JobType)
.Single(j => j.Id == job.Id);
// Update scalar/complex properties
context.Entry(originalJob).CurrentValues.SetValues(job);
// Update reference
originalJob.JobType = job.JobType;
context.SaveChanges();
}
您很可能也利用了一些招数在您的情况:
You could probably also leverage some "tricks" in your case:
using (var context = new JobContext())
{
var jobType = job.JobType;
job.JobType = null;
context.JobTypes.Attach(jobType);
context.Jobs.Attach(job);
// change detection starts from here,
// EF "thinks" now, original is JobType==null
job.JobType = jobType;
// change detection will recognize this as a change
// and send an UPDATE to the DB
context.Entry(job).State = EntityState.Modified; // for scalar/complex props
context.SaveChanges();
}
如果你想设置它不会工作,虽然 JobType
到空
。
It wouldn't work though if you want to set JobType
to null
.
这是这是越来越简单得多的典型情况如果你暴露外键模型中的属性:以 JobTypeId
在工作
实体您的代码会工作,因为FK属性是标量,状态设置为修改
也将标记为修改这个属性。
This is a typical situation which is getting much simpler if you expose foreign keys as properties in your model: With a JobTypeId
in your Job
entity your code would work because the FK property is scalar and setting the state to Modified
will also mark this property as modified.
这篇关于更新到实体框架4.1的子对象的引用(CodeFirst)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!