Generic Method of a Generic Class C # for similar classes

0

I have some classes that will use a write method. I created a CRUD (Generic) class where I would have a write method, but I need this method to take classes as a parameter.

There is some way to create a generic method for what I have read, but I was unable to pass one type of parameter that caters to all classes.

For example, this same method will write the company, contact, client in the bank, being the add function of EF.

Below is a method that I created, but it only serves the Enterprise class in this case.

public void Gravar<T>(Empresa obj)
    {
        context.Empresa.Add(obj);
    }

How do you make it work for the Contact, Client, User, etc. class instead of Company? The way it is I would have to create a record () for each class.

    
asked by anonymous 23.05.2018 / 14:08

2 answers

0

You need to pass the generic entity in the parameter, it would look like this

public void Gravar<T>(T obj)
{
    context.Set<T>().Add(obj);
} 

To call this you just need to pass the object as a parameter, it will understand the type of it

Empresa empresa = new Empresa
{
    Nome = "Empresa"
};

Gravar(empresa);
    
23.05.2018 / 14:32
0

How I did it: In my class CRUD (Generic) I left like this:

public class Crud
        {
        public void Gravar(T obj)
        {
            context.Set<T>().Add(obj);
            context.SaveChanges();
        }

        private readonly ModelConexao context;

        public Crud(ModelConexao _context)
        {
            context = _context;
        }

And in my form class I called the method like this:

protected void btnGravar_Click(object sender, EventArgs e)
        {
            using (ModelConexao db = new ModelConexao())
            {
                T emp = new T()
                {                   
                    dominio = txtEmpresa.Text.Split(' ').FirstOrDefault(),
                    banco = "empresa_" + txtEmpresa.Text.Split(' ').FirstOrDefault(),
                    nome = txtEmpresa.Text.ToString()
                };

                Crud empresa = new Crud(db);
                empresa.Gravar(emp);

I just had to instantiate the Crud class, and I think the correct one would be some way of not having to instantiate for each entity, because in that same code I have to give a Write to the Contact entity.

But thanks for the help! Little by little I'm learning ...

    
23.05.2018 / 15:56