Returning the values of a model dynamically in . NET MVC

Asked

Viewed 98 times

3

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

Example:

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

However, in this authentication class there is the method Get(), which must return the user data stored in the database through the model that receives as parameter the name of the Session guard_name and the value thereof.

public <guard_name> Get()
{
    ...

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

The problem is that as 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 solve?

1 answer

5


Interfaces can be a good starting point. Implement an interface for the 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 get a guy, not another string.

Authentication.Guard(User).Attempt(user.id);

Browser other questions tagged

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