Convert generic to specific type in DB set

Asked

Viewed 19 times

0

I am creating a web api using . net 5

The purpose of the application is to make a simple user registration, and in the future other types of registration

I created a generic CRUD interface to be used on all other specific interfaces

public interface IbaseRepository
{
    void Criar<T>(T obj);

    void Editar<T>(T obj);

    void Deletar<T>(T obj);
}

User Interface

public interface IUsuarioRepository : IbaseRepository
{
    ICollection<Usuario> ObterTodos();
}

My User class is still incomplete, but I’ll still put it here

[Table("Cliente")]
public class Usuario
{
    [Key]
    [Column("cd_id", TypeName = "numeric(10)")]
    public int Id { get; set; }
    [Required]
    [MaxLength(50)]
    public string Login { get; set; }
    public string Senha { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
    public DateTime DataCadastro { get; set; }
    public bool Ativo { get; set; }
    [InverseProperty("Historico")]
    public ICollection<Historico> Historico { get; set; }
    [ForeignKey("Historico")] 
    public Historico HistoricoId { get; set; }
}

My doubt is at this point here

As the interface receives as parameter a Generic type, I cannot pass to the add function because it expects an object of type User. How do I convert Generic type into specific type

Note: I am using the Entity Framework Core V 5.0.8

1 answer

1


Its interface has to be generic...

public interface IbaseRepository<T>
{
    void Criar(T obj);

    void Editar(T obj);

    void Deletar(T obj);
}

And then you pass the kind on the inheritance:

public interface IUsuarioRepository : IbaseRepository<Usuario>
{
    ICollection<Usuario> ObterTodos();
}
  • 1

    Thanks for the help Rovann

  • 2

    But one thing that should be emphasized in this reply is that the User class will replace the letter T by the class public void Edit(User obj) { throw new Notimplementedexception(); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.