In many projects I have to make a table containing users and implementing standard user-based functions such as authentication, saving, etc. So I decided to make a class library containing these functionalities, for example:
public class User
{
public int? Id {get;set;}
public string UserName {get;set;}
public string Password {get;set;}
}
public class MyDbContext : DbContext
{
public DbSet<User> {get;set;}
}
public class UserService
{
public MyDbContext Context {get;set;} // will be initialized in constructor
public User GetByUserName(string username)
{
return (from s in Context.Users where s.UserName.Equals(username) select s).SingleOrDefault();
}
// etc...
}
Now when I start a new Mvc project I add this library and extends the DbContext with custom models. The problem is I don’t know how to extend the User table with some additional fields, for example:
public class MyUser : User
{
public bool IsApproved {get;set;}
}
public class CustomDbContext : MyDbContext
{
public DbSet<SomeOtherModel> {get;set;}
// problem: override DbSet in MyDbContext with class MyUser?
//public DbSet<MyUser> {get;set;}
}
In this case I also need to override the DbSet<User> of the MyDbContext. If I remove the DbSet<User> in the library my UserService class won’t work anymore. Any ideas how to make an extensible framework?
You could use generics (I haven’t tested this, just a thought):
And then inherit:
And the same generic in the
UserService: