Red*_*don 7 asp.net-mvc entity-framework windows-services asp.net-mvc-4 entity-framework-5
我在针对.Net 4.5的Windows服务中使用此代码,该服务使用数据库优先的Entity Framework层:
var existingState = DataProcessor.GetProcessState(workerId);
existingState.ProcessStatusTypeId = (int)status;
existingState.PercentProgress = percentProgress;
existingState.ProgressLog = log;
DataProcessor.UpdateProcessState(existingState);
Run Code Online (Sandbox Code Playgroud)
而这个代码在同一个解决方案中的数据处理类中:
public ProcessState GetProcessState(int id)
{
using (var context = new TaskManagerEntities())
{
var processes = (from p in context.ProcessStates.Include("ProcessType").Include("ProcessStatusType")
where p.IsActive && p.ProcessStateId == id
select p);
return processes.FirstOrDefault();
}
}
public ProcessState UpdateProcessState(ProcessState processState)
{
using (var context = new TaskManagerEntities())
{
context.ProcessStates.Add(processState);
context.Entry(processState).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
return processState;
}
Run Code Online (Sandbox Code Playgroud)
ProcessState是另外两个类(ProcessStatusType和ProcessType)的父级.当我在Windows服务中运行该代码时,它会检索记录,更新实体并保存它.尽管ProcessType子元素从未在上面的代码中使用,但是当执行ProcessState实体上的保存时,EF会在ProcessType表上执行插入操作并在其中创建新记录.然后,它更改ProcessStatus实体中的FK,将其指向新子项并将其保存到数据库中.
它并没有在ProcessStatusType表,设置了基本相同的FK父子关系做到这一点.
我现在有一个完全相同的ProcessType条目的数据库,我不需要,我不知道为什么会这样.我觉得我犯了一些我无法看到的明显错误,因为这是我的第一个EF项目.问题是我允许上下文在调用之间到期但是保持相同的实体吗?
使用Add将所有元素的状态设置为Added,这将导致插入子元素.在为此元素指定EntityState.Modified时未插入父元素.
尝试在UpdateProcessState中使用以下内容,而不是使用Add.
context.ProcessStates.Attach(processState);
context.Entry(processState).State = EntityState.Modified;
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
Attach将所有元素的状态设置为Unchanged,并通过为父元素指定Modified来指示只应更新此元素.
另一个注意事项.你应该使用强类型Include(x => x.ProcessType)而不是Include("ProcessType").
| 归档时间: |
|
| 查看次数: |
4903 次 |
| 最近记录: |