简体   繁体   中英

Use same db table from different entities in Entity Framework- Code first

I have used Entity Framework database first few times. Now, I'm trying to approach code first. I am little bit confused in some places. Lets say, I would like to have two classes- ApplicationUser & CurrentUser . All of these classes intended to use the same database table Users . The structure of Users table looks like-

-----------------------------------------------------------------------------------------------------------
UserId | FullName | Designation | LoginName | LoginPassword | CreatedDateTime | IsActive | FewOtherFields |
-----------------------------------------------------------------------------------------------------------

Here are the classes details-

//Will be used to add,edit, delete records for new user.
ApplicationUser
{
   UserId 
   FullName
   Designation 
   LoginName 
   LoginPassword 
   CreatedDateTime 
   IsActive
   ...
   OtherProperties
   ...
}

//Will be used to login and other purposes.
CurrentUser
{
   UserId 
   FullName
   Designation 
   LoginName 
   LoginPassword  
   IsActive
}

Might be this is an easy thing, or there are tricky techniques to achieve this. Any help?

You can use Table per Hierarchy inheritance strategy:

public class CurrentUser
{
    //some properties
}

public class ApplicationUser : CurrentUser
{
    //additional properties
}

public class MyContext : DbContext
{
    public DbSet<CurrentUser> Users { get; set; }
}

Usage:

IQuerable<CurrentUser> currentUsers = context.Users;
IQuerable<ApplicationUser> applicationUsers = context.Users.OfType<ApplicationUser>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM