Контекст некорректно создает экземпляр сущности, используя метод Set
Использовал данную архитектуру для создания своего приложения. Приложение представляет собой простой телеграм бот, который общается с локальным хостом. Сущности из бд, которые используются в бд работают корректно за исключением одной.
При её деплое в репозиторий возникает исключение:
Как уже говорил ранее, с другими сущностями проблем не возникало и операции с бд работали корректно. Код, где задействован данный функционал прикрепляю ниже:
Контекст данных
public class StoreContext:DbContext
{
public StoreContext(DbContextOptions<StoreContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
new ProductBuilder(modelBuilder.Entity<Product>());
new CustomerBuilder(modelBuilder.Entity<Customer>());
new OrderBuilder(modelBuilder.Entity<Order>());
new FileOnlineBuilderBuilder(modelBuilder.Entity<FileOnline>());
}
}
Сервис, сохраняющий новый файл
public class FileService : IFileService
{
private IFileRepository _repository;
private ILogger<FileOnline> _logger;
private StoreContext _context;
private readonly IMapper _mapper;
public FileService(IFileRepository repository, StoreContext context, IMapper mapper, ILogger<FileOnline> logger)
{
_logger = logger;
_mapper = mapper;
_repository = repository;
_context = context;
}
public IEnumerable<string> GetFilesId()
{
var collectionId = _repository.GetAll();
return collectionId.Select(_mapper.Map<FileDTO>).Select(f=>f.FileId);
}
public void SetFileId(FileDTO file)
{
if (!string.IsNullOrEmpty(file.FileId))
{
_repository.Add(_mapper.Map<FileOnline>(file));
_context.SaveChanges();
_logger.LogInformation("File id was succesfully stored");
return;
}
_logger.LogError("It was handled exception while receiving a file id");
}
}
Интерфейс для базового класса репозитория
public interface IRepository<T> where T: BaseEntity
{
T Get(Guid id);
IEnumerable<T> GetAll();
void Add(T entity);
T Update(T updatetEntity);
bool Delete(T removedEntity);
}
Базовый класс репозитория
public abstract class Repository<T> : IRepository<T> where T:BaseEntity
{
protected readonly DbSet<T> _entity;
public Repository(StoreContext context)
{
_entity = context.Set<T>();
}
public void Add(T entity)
{
if (entity != null)
{
if (_entity.Contains(entity))
return;
_entity.Add(entity);
}
}
public bool Delete(T removedEntity)
{
if (removedEntity != null)
{
_entity.Remove(removedEntity);
return true;
}
return false;
}
public T Get(Guid id)
{
return _entity.FirstOrDefault(e => e.Id == id);
}
public IEnumerable<T> GetAll() => _entity.AsEnumerable();
public T Update(T updatetEntity)
{
if (updatetEntity != null)
{
var returnedEntity = _entity.Update(updatetEntity).Entity;
return returnedEntity;
}
return updatetEntity;
}
}
Сам репозиторий
public class FileRepository : Repository<FileOnline>, IFileRepository
{
public FileRepository(StoreContext context) : base(context)
{
}
}
IFileRepository просто наследуется от IRepository<сущность>
Конфигурация DependencyInversion:
services.AddDbContext<StoreContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"])
.UseLoggerFactory(LoggerFactory.Create(config => config.AddConsole()));
});
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddTelegramBot(Configuration);
services.AddTransient<ICommandTelegramService, CommandTelegramService>();
services.AddTransient<IFileService, FileService>();
services.AddTransient<IOrderService, OrderService>();
services.AddTransient<ICustomerService, CustomerService>();
services.AddTransient<ITelegramBotService, TelegramBotService>();
services.AddScoped<IFileRepository, FileRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
Все сервисы- Transient, Репозитории- Scoped
FileDTO:
public class FileDTO
{
public string FileId { get; set; }
public string Description { get; set; }
}
FileOnline
[Table("Files")]
public class FileOnline : BaseEntity
{
public string Description { get; set; }
public string FileId { get; set; }
}
FileBuilder
public FileOnlineBuilderBuilder(EntityTypeBuilder<FileOnline> builder)
{
builder.HasKey(f => f.Id);
builder.Property(f => f.FileId);
builder.Property(f => f.Description);
}