我有一个使用Entity Framework Core和ASP.NET Core 2.1编写的代码优先的Web应用程序。 当我保存数据时,有时只保存1条记录即可。但是有时它会保存2条具有不同ID的重复记录。
Create(company)
方法仅从控制器调用一次,但有时会创建两个公司。
控制器实现:
[ApiController]
public class CompaniesController : ControllerBase
{
private readonly ICompanyManager _companyManager;
public CompaniesController(IEmpresaManager companyManager)
{
_companyManager = companyManager;
}
[HttpPost]
public async Task<IActionResult> Post(CompanyBindingModel companyViewModel)
{
try
{
await _companyManager.Create(_mapper.Map<Company>(companyViewModel));
}
catch (Exception ex)
{
return Conflict(ex.Message);
}
return Ok(new { Mensagem = "Company created successfully" });
}
管理器实现:
public class CompanyManager : ICompanyManager
{
private readonly RepositoyBase<Company, long> _repository;
public CompanyManager (RepositoyBase<Company, long> repository) {
_repository = repository;
}
public async Task<long> Create(Company company)
{
_repository.Add(company);
await _repository.SaveChangesAsync();
return company.Id;
}
}
这是我的存储库模式实现,它保存所有实体。 通过依赖项注入来注入DbContext,并将其注册为作用域。
在Startup.cs
services.AddScoped<DbContext, ApplicationDbContext>();
存储库实现
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace MyProject.Repositories
{
public class RepositoryBase<TEntity, TKey> : IRepositoryBase<TEntity, TKey>
where TEntity : class, IEntity<TKey>
where TKey : struct
{
protected readonly DbContext _dbContext;
public RepositoryBase(DbContext dbContext)
{
_dbContext = dbContext;
}
public virtual async Task<IEnumerable<TEntity>> GetAll(Expression<Func<TEntity, bool>> expression)
{
return await _dbContext.Set<TEntity>().Where(expression).ToListAsync();
}
public virtual async Task<TEntity> Get(Expression<Func<TEntity, bool>> expression)
{
return await _dbContext.Set<TEntity>().FindAsync(expression);
}
public virtual async Task<TEntity> GetById(TKey id)
{
return await _dbContext.Set<TEntity>().FindAsync(id);
}
public virtual IQueryable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>().AsNoTracking();
}
public virtual void Add(TEntity entity)
{
_dbContext.Set<TEntity>().Add(entity);
}
public virtual void Update(TEntity entity)
{
_dbContext.Set<TEntity>().Update(entity);
}
public virtual void Remove(TEntity entity)
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbContext.Attach(entity);
}
_dbContext.Set<TEntity>().Remove(entity);
}
public virtual void Remove(TKey id)
{
TEntity entityToRemove = _dbContext.Set<TEntity>().Find(id);
_dbContext.Set<TEntity>().Remove(entityToRemove);
}
public virtual async Task SaveChangesAsync()
{
await _dbContext.SaveChangesAsync();
}
}
}
这是由于我的存储库实现,DbContext注册为作用域还是具有线程安全性引起的?