Returning the values of a model dynamically in .NET MVC

3

I have an authentication class that stores the user ID in a session, which receives the model name corresponding to the current user, such as users, admins, clients.

Example:

Authentication.Guard("users").Attempt(user.id)

However, in this authentication class there is the Get() method, which should return the user data stored in the database through the model that receives the session name guard_name as its parameter.

public <guard_name> Get()
{
    ...

    using (Entities db = new Entities())
    {
        return db.<guard_name>.Where(p => p.id == session)
            .FirstOrDefault();
    }
}

The problem is that since the name of session guard_name can vary between users, admins and clients, I need a more dynamic return form or maybe use some interface.

How can I resolve?

    
asked by anonymous 28.06.2016 / 21:09

1 answer

5

Interfaces can be a good starting point. Implement an interface for all three types:

public class User : IMinhaInterface { ... }
public class Admin : IMinhaInterface { ... }
public class Client : IMinhaInterface { ... }

Get() would look like this:

public IMinhaInterface Get<T>()
    where T: class, IMinhaInterface
{
    ...

    using (Entities db = new Entities())
    {
        return db.Set<T>.FirstOrDefault(p => p.id == session);
    }
}

Guard would receive a type, not a string .

Authentication.Guard(User).Attempt(user.id);
    
28.06.2016 / 21:16