首先是EF代码 - 将子类属性映射到基类表

时间:2013-07-31 20:14:26

标签: asp.net entity-framework ef-code-first

我想知道是否可以将子类属性映射到基类表。说我有两个课程(缩短):

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(每种类型的表)继承(这意味着两个表 - 用户和客户)。出于某些原因,我希望在User表中具有ShopId属性,但在Customer表中具有来自Customer类的所有其他属性。这甚至可能吗?

在User表中使用ShopId列可以让我们在Username和ShopId上创建唯一索引(该应用程序是多租户的,因此我们不需要全局唯一的用户名,只需要商店级别的唯一用户名)。

1 个答案:

答案 0 :(得分: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 });
    }
}
相关问题