EF Fluent定义外键主键

时间:2012-04-09 16:51:52

标签: entity-framework-4.1 fluent

我已经定义了一组Code First实体:

public class User
{
    public int UserId { get; set; }
    public string username { get; set; }
}
public abstract class UserType
{
    public virtual User User { get; set; }
    public int UserId { get; set; }
}
public class RoleUser : UserType
{
    public string role { get; set; }
}
public class SiteUser : UserType
{
    public string site { get; set; }
}

public class Testctx:DbContext
{
    static Testctx()
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<Testctx>());
    }

    public DbSet<User> Users { get; set; }
    public DbSet<SiteUser> SiteUsers { get; set; }
    public DbSet<RoleUser> RoleUsers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasKey(u=>u.UserId).ToTable("User");
        modelBuilder.Entity<RoleUser>().HasKey(u => u.UserId).ToTable("RoleUser");
        modelBuilder.Entity<SiteUser>().HasKey(u => u.UserId).ToTable("SiteUser");
    }

}

如果我希望User,RoleUser,SiteUser,每个都有一个名为“ID”的ID列,如何在Usertype中保持与用户的外键主键关系时实现此目的。

例如,如果我声明公共类Entity {public int ID {get; set;}}并且都从Entity继承,那么我将在RoleUser和SiteUser中留下UserId和ID字段。

0 个答案:

没有答案