The scenario is as follows: I have an Employee class. The primary key
of it should be the employee's CPF that the user types.
The problem: key
follows a default auto increment, not going according to the entered CPF.
EX: I have entered an employee's CPF number: 492.203.120-90 if it is the first; When the table record persists, the key will be entered with a value of 1.
Employee Class:
public class Funcionario
{
[Key]
[Display(Name="CPF: ")]
[Range(0,long.MaxValue)]
[Cpf(ErrorMessage = "Valor Inválido para CPF!")]
public long FUN_CPF { get; set; }
[Required(ErrorMessage = "Digite o nome do funcionário!")]
[MinLength(5, ErrorMessage = "O tamanho mínimo do nome são 5 caracteres.")]
[StringLength(64, ErrorMessage = "O tamanho máximo são 64 caracteres.")]
[Display(Name = "Nome: ")]
public string FUN_NOME { get; set; }
[Display(Name = "Data de Nascimento: ")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime FUN_DTNASCIMENTO { get; set; }
[Display(Name = "Cargo: ")]
[MinLength(5, ErrorMessage = "O tamanho mínimo do nome são 5 caracteres.")]
[StringLength(64, ErrorMessage = "O tamanho máximo são 64 caracteres.")]
public string FUN_CARGO { get; set; }
[Display(Name = "Data de Adminssão: ")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime FUN_DTADMISSAO { get; set; }
[Display(Name = "Data de Demissão: ")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime? FUN_DTDEMISSAO { get; set; }
//Data pós demissão desativar funcionario
[Display(Name = "Ativo: ")]
public bool FUN_ATIVO { get; set; }
}
Methodology for CRUD is as follows:
public interface IGenericRepository<TEntity>
{
Task<TEntity> GetByIdAsync(int id);
IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate);
IQueryable<TEntity> GetAll();
Task EditAsync(TEntity entity);
Task InsertAsync(TEntity entity);
Task DeleteAsync(TEntity entity);
// Task Dispose(TEntity entity);
}
The implementation:
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> DbSet;
private readonly DbContext _dbContext;
public GenericRepository(DbContext dbContext)
{
_dbContext = dbContext;
DbSet = _dbContext.Set<TEntity>();
}
public GenericRepository()
{
}
public IQueryable<TEntity> GetAll()
{
return DbSet;
}
public async Task<TEntity> GetByIdAsync(int id)
{
return await DbSet.FindAsync(id);
}
public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return DbSet.Where(predicate);
}
public async Task EditAsync(TEntity entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
public async Task InsertAsync(TEntity entity)
{
DbSet.Add(entity);
await _dbContext.SaveChangesAsync();
}
public async Task DeleteAsync(TEntity entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}