【发布时间】:2017-01-30 15:13:34
【问题描述】:
通过使用 Entity Framework 6 以及存储库模式,我尝试更新一行,其中现有行有一个与之关联的新外键对象。例如,Person 记录已存在。 Person 得到一个新的Dog。所以现在Person 类有一个Dog 属性实例化并填充了数据。
这是我的更新方法:
public async Task<TObject> UpdateAsync(TObject updated, int key)
{
if (updated == null)
return null;
var existing = await this._context.Set<TObject>().FindAsync(key);
if (existing != null)
{
this._context.Entry(existing).CurrentValues.SetValues(updated);
}
await this._context.SaveChangesAsync();
return existing;
}
我通过以下方式调用它:
personRecord.Dog = new Dog () { Name = "Max", Age = 7 };
await this.PersonRepository.UpdateAsync(personRecord, personRecord.Id)
但是没有新的Dog 记录被插入到数据库中。我做错了什么?
【问题讨论】:
-
显示您的
Person课程 -
@haim770
Person只是一个示例,但我将使用 EF 生成的模型更新问题。顺便说一句,当我插入并执行插入代码时,它可以工作 -
SetValues 只会更新标量值,不会更新相关属性。相关问题:stackoverflow.com/questions/21426884/…
-
@SteveGreene 谢谢我去看看
-
@SteveGreene 根据您提供的链接,这是唯一的方法吗?在所有的EF类上实现一个接口感觉很麻烦
标签: c# entity-framework-6 repository-pattern