本文介绍了EF7 beta6:保存多个实体时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET5 和 Entity Framework 7.0.0-beta 6 创建 API,当我尝试在多个请求中执行各种更新时,出现此异常:

I am creating an API using ASP.NET5 and Entity Framework 7.0.0-beta 6, and when I try to execute various updates in several requests, I get this Exception:

无法跟踪公司",因为已经在跟踪具有相同键的此类型的另一个实例.对于新实体,请考虑使用 IIdentityGenerator 生成唯一键值.

这是我的代码:

public class MrBellhopContext : DbContext
{

    public DbSet<Company> Company { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>(entity =>
        {
            entity.Key(c => c.CompanyId);

            entity.Index(c => c.Name);

            entity.Property(c => c.CompanyId).ValueGeneratedOnAdd();
        });

        modelBuilder.UseSqlServerIdentityColumns();

        base.OnModelCreating(modelBuilder);
    }

}


public class Company
{

    public int CompanyId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string Phone { get; set; }

    public string Email { get; set; }

    public short StatusId { get; set; }

}


public class CompanyRepository : ICompanyRepository
{

    MrBellhopContext _dbcontext;


    public async Task UpdateAsync(Company company)
    {
        _dbcontext.Update(company);
        await _dbcontext.SaveChangesAsync();
    }
}



[Route("api/[controller]")]
public class CompanyController : Controller
{


    [HttpPut]
    public async void UpdateAsync([FromBody] Company company)
    {
        if ((!ModelState.IsValid) || (company == null))
        {
            Context.Response.StatusCode = 400;
            return;
        }
        else
        {
            await _repository.UpdateAsync(company);
        }
    }

}

我尝试通过删除 ValueGeneratedOnAdd()UseSqlServerIdentityColumns() 或更改映射来解决它,但是如果我尝试在多个请求中更新多个实体,我获取异常:

I have tried to solve it by removing ValueGeneratedOnAdd(), UseSqlServerIdentityColumns() or changing the mapping, but if I try to update several entities in several requests, I get the Exception:

  1. 第一个请求:更新 CompanyId 8
  2. 第一个请求:更新 CompanyId 9 !!错误

有人知道如何解决这个问题吗?

推荐答案

已解决:https://github.com/aspnet/EntityFramework/issues/2652

我将存储库添加为单例:

I was adding Repository as a Singleton:

services.AddSigleton<Data.Interfaces.Company.ICompanyRepository,Data.Repositories.Company.CompanyRepository>();

这意味着所有请求都共享存储库的单个实例.您应该将其减少到 Scoped,以便每个请求都有一个存储库实例.除了避免您遇到的问题之外,它还将确保您最终不会得到一个巨大的上下文实例来跟踪内存中数据库中的所有数据.

解决:

services.AddScoped<Data.Interfaces.Company.ICompanyRepository,Data.Repositories.Company.CompanyRepository>();

这篇关于EF7 beta6:保存多个实体时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:23