简体   繁体   English

在实体框架中使用来自不同实体的相同数据库表-代码优先

[英]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 . 可以说,我想拥有两个类: ApplicationUserCurrentUser All of these classes intended to use the same database table Users . 所有这些类都打算使用相同的数据库表Users The structure of Users table looks like- Users表的结构看起来像-

-----------------------------------------------------------------------------------------------------------
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>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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