2013-07-31 59 views
0

我不知道是否可以将子类属性映射到基类表。说我有两个班(缩短):EF代码优先 - 将子类属性映射到基类表

public abstract class User 
{ 
    [Key] 
    public int UserId { get; set; } 

    public string Username { get; set; } 

    // other properties... 
} 

public class Customer : User 
{ 
    public int ShopId { get; set; } 

    public virtual Shop Shop { get; set; } 

    // other properties... 
} 

我使用TPT(每种类型的表)继承(这意味着两个表 - 用户和客户)。由于某些原因,我希望在用户表中有ShopId属性,但在Customer表中有Customer类中的所有其他属性。这甚至可能吗?

在User表中有ShopId列允许我们在用户名和ShopId上创建唯一索引(应用程序是多租户的,所以我们不需要全球唯一的用户名,只有商店级的唯一用户名)。

+0

小号o为什么不能将shopId放入用户? ef不会为摘要创建表格。 –

+0

这是使用TPT时。此外,我不想从'用户'和'商店'有任何关系。 'User'与'Shop'无关,只有'Customer'。 – MrHenkey

回答

0

这是你在找什么?

UserBase.cs

public abstract class UserBase 
{ 
    public int UserId { get; set; } 
    public string Username { get; set; } 
    public int ShopId { get; set; } 
    public virtual Shop Shop { get; set; } 
} 

User.cs

public class User : UserBase 
{ 
    // user specific properties... 
} 

Customer.cs

public class Customer : UserBase 
{ 
    // customer specific properties... 
} 

UserDbContext.cs

public class UserDbContext : DbContext 
{ 
    ... 

    protected override OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // if you want users and customers to be shop specific 
     modelBuilder.Entity<UserBase>.HasKey(x => new { x.UserId, x.ShopId }); 

     // if you only want users to be shop specific uncomment below and remove above 
     //modelBuilder.Entity<User>.HasKey(x => new { x.UserId, x.ShopId }); 
    } 
} 
+0

不完全。我正在寻找一个解决方案,无需从用户(基类)到Shop(应用程序级别)的关系。我的意思是,既然与Shop的关系只对客户有效,我更愿意在Customer类中拥有“ShopId”和“Shop”属性。但是,为了确保数据库的完整性,最好在User表中有ShopId列。映射到属性的列仅在Customer类中可见。 – MrHenkey

+0

只需将'ShopId'属性添加到'User'类,然后将导航属性添加到'Shop'。 – shuniar