Reputation:
I want to make a derived class for my User object that has some extra properties (LoginUser class), but entity framework then returns the derived class when I fetch a User from the database. This is unwanted.. The derived class has no parameter-less constructor and should only be created as a wrapper for the login.. So I added to this to the onCreateModel:"
modelBuilder.Ignore<LoginUser >();
But now when I try to store or reference my LoginUser object it throws an exception saying the entity has no mapping (LoginUser). How can I make entity framework use the mappings for the base class?
This are my classes:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Role { get; set; }
}
public class LoginUser : User, IPrincipal
{
private IPrincipal underlayingPrincipal;
public IIdentity Identity
{
get
{
return this.underlayingPrincipal.Identity;
}
}
public LoginUser(IPrincipal principal, User user)
{
this.underlayingPrincipal = principal;
this.Id = user.Id;
this.Name = user.Name;
this.Role = user.Role;
}
public bool IsInRole(string role)
{
return this.Role == role;
}
}
Upvotes: 1
Views: 1962
Reputation: 286
LoginUser should't extend User; it should be an independent class that you would map from/to User when you retrieve/store your user. Database model class should stay for database, and the classes you pass to the views should be independent and mapped from the database model.
If anyway you want to pass you User class to the model, you could just make a partial class of User and add the complementary inof (properties, interfaces...)
partial class User
{
private IPrincipal underlayingPrincipal;
public IIdentity Identity
{
get
{
return this.underlayingPrincipal.Identity;
}
}
public User(IPrincipal principal, User user)
{
this.underlayingPrincipal = principal;
this.Id = user.Id;
this.Name = user.Name;
this.Role = user.Role;
}
public bool IsInRole(string role)
{
return this.Role == role;
}
}
Upvotes: 1