0

我目前正在嘗試使用.net核心和EF核心。Entity Famework core - 實體類型的實例無法跟蹤,因爲具有相同密鑰的此類型的另一個實例已被跟蹤

我有以下代碼更新數據

protected void Update(T entity, bool saveChanges = true) 
{ 
    _context.Set<T>().Attach(entity); 
    _context.Entry(entity).State = EntityState.Modified; 
    if (saveChanges) _context.SaveChanges(); 
} 

類我更新

public partial class Blog 
{ 
    public Blog() 
    { 
     Post = new HashSet<Post>(); 
    } 

    public int BlogId { get; set; } 
    public string Url { get; set; } 

    public virtual ICollection<Post> Post { get; set; } 
} 

當我嘗試更新的任何條目中的第一次,它是成功的。我第二次更新相同的條目,我得到下面的錯誤:

System.InvalidOperationException: 'The instance of entity type 'Blog' 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.'

同樣出現爲每個條目,成功首次和失敗第二次。

其它信息: 我得到使用下面的代碼中的所有數據:上面作爲視圖的表

protected IEnumerable<T> GetAll() 
{ 
    return _context.Set<T>().AsNoTracking().AsEnumerable(); 
} 

顯示。 DTO被用來在數據和web層之間進行通信。

上下文註冊在啓動如下

services.AddDbContext<BloggingContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

我的問題是爲什麼會出現第二次更新,以及如何解決它在一個錯誤。謝謝。

+0

您使用的是BlogRepository嗎?你能告訴我們,像你告訴服務在啓動時注入庫嗎? – alessalessio

+0

'services.AddScoped ();'這是如何使用BlogRepository啓動 – gvk

+0

異常意味着您試圖將具有相同鍵的兩個實體實例附加到上下文。當啓動時注入一個存儲庫的單例實例時會發生這種情況。你能上傳你的項目代碼並分享嗎? – alessalessio

回答

0

您的服務提供商是靜態的,所以它實際上是單身人士。 如此處所示 github.com/aspnet/EntityFramework/issues/2652

該異常意味着您試圖將具有相同鍵的兩個實體實例附加到上下文。當啓動時注入一個存儲庫的單例實例時會發生這種情況。

I D建議從一個抽象類,改變你的通用存儲庫到一個接口,並啓動期間注射合適的庫:

services.AddScoped<IRepository<Blog>, BlogRepository>(); 
services.AddScoped<IRepository<Post>, PostRepository>(); 

,而不是你靜態的ServiceProvider這實際上提供了一個單獨的實現你的BlogRepository的

相關問題