首页 新闻 赞助 找找看

EF Core修改数据上下文不一致的问题

0
悬赏园豆:20 [已解决问题] 解决于 2017-02-13 19:23

请问下EF Core在修改数据的时候提示:

An unhandled exception occurred while processing the request.

InvalidOperationException: The instance of entity type 'WebInfomation' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

Add

 

Startup代码如下:

services.AddEntityFrameworkSqlServer().AddDbContext<Repositories.Context.Content>(bulider =>
{
bulider.UseSqlServer("server=.;database=yy;uid=sa;password=123456", options =>
{
});
}, ServiceLifetime.Scoped);

 

实现代码如下:

public async Task ModifyAsync(TAggregateRoot root)
{
DbSet.Update(root).State = EntityState.Modified;
await DbContext.SaveChangesAsync();
}

 

DbContext是通过构造注入来的:

public BaseRepository(YYCMSContent dbcontext)
{
DbContext = dbcontext;
}

 

搞了好久了,希望老司机带下。

大壮他哥的主页 大壮他哥 | 初学一级 | 园豆:11
提问于:2017-01-31 17:24
< >
分享
最佳答案
0

1.上下文没管理好

2.你封装了ef.手动去修改追踪状态

收获园豆:10
吴瑞祥 | 高人七级 |园豆:29449 | 2017-02-01 00:08
其他回答(1)
0

建议提供更多一些的代码

收获园豆:10
dudu | 园豆:31075 (高人七级) | 2017-01-31 19:37

我刚才尝试了下不让它跟踪数据,就可以了。

但是我觉得ServiceLifetime.Scoped这个指定没有起作用。

支持(0) 反对(0) 大壮他哥 | 园豆:11 (初学一级) | 2017-01-31 19:38

@大壮他哥: 出现这个问题恰恰说明ServiceLifetime.Scoped起作用了

支持(0) 反对(0) dudu | 园豆:31075 (高人七级) | 2017-01-31 19:47

@dudu: 不解,麻烦说一下。

支持(0) 反对(0) 大壮他哥 | 园豆:11 (初学一级) | 2017-01-31 19:47

@大壮他哥:

对于同一个DbContext实例,同一个类型、同一个Key的实体的实例,只能被跟踪一次。

使用ServiceLifetime.Scoped,对于同一个http请求,会共享同一个DbContext实例。

我的猜测:你遇到这个问题,是由于处理当前http请求的代码中,出现了2个key相同的WebInfomation实例,当对第2个WebInfomation实例,进行  DbSet.Update(root).State = EntityState.Modified; 操作时,就触发了"The instance of entity type 'WebInfomation' cannot be tracked because another instance of this type with the same key is already being tracked." 异常。

支持(0) 反对(0) dudu | 园豆:31075 (高人七级) | 2017-01-31 20:09

@dudu:  谢谢,应该是这个问题。

支持(0) 反对(0) 大壮他哥 | 园豆:11 (初学一级) | 2017-02-06 12:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册