Entity Framework 继承组合键
Entity Framework inheritance composite key
这是我的场景:我有三种实体类型,User(id, email, password),Volunteer(name, birthdate. ..) 和 NonProfit(地址...)。志愿者和非营利组织都是用户。
我能够创建三个 table,如 tbUser、tbVolunteer 和 tbNonProfit,其中用户有一个主键,志愿者和非营利组织有 primary/foreign 用户键(用户 ID),但我不想要这个。
我的用户不是抽象的class。首先,我将创建一个用户,例如 Mary,我会说 Mary 属于 Volunteer 类型。下一刻,Mary 将登录并完成注册,因此我将在数据库中创建一个志愿者行。
简而言之,我希望志愿者 table 将 UserID 作为外键和 VolunteerID(主键),以使其与我的工程图表相同,其中志愿者和非营利组织是用户。我不想要聚合或组合,因为在我的 UML 志愿者中继承自用户。
我愿意接受建议,谢谢大家
正确的实现方式是不要有另一个主键。实现如下所示:
public class User
{
[Key]
public int UserId { get; set; }
public string Email{ get; set; }
public string Password { get; set; }
}
[Table("Volunteer")]
public class Volunteer : User
{
public DateTime BirthDate { get; set; }
}
[Table("NonProfit")]
public class NonProfit: User
{
public string Address { get; set; }
}
public class MyContext: DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Volunteer> Volunteers { get; set; }
public DbSet<NonProfit> NonProfits { get; set; }
}
有关更多信息,请查看这篇文章:http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type
这是我的场景:我有三种实体类型,User(id, email, password),Volunteer(name, birthdate. ..) 和 NonProfit(地址...)。志愿者和非营利组织都是用户。
我能够创建三个 table,如 tbUser、tbVolunteer 和 tbNonProfit,其中用户有一个主键,志愿者和非营利组织有 primary/foreign 用户键(用户 ID),但我不想要这个。
我的用户不是抽象的class。首先,我将创建一个用户,例如 Mary,我会说 Mary 属于 Volunteer 类型。下一刻,Mary 将登录并完成注册,因此我将在数据库中创建一个志愿者行。
简而言之,我希望志愿者 table 将 UserID 作为外键和 VolunteerID(主键),以使其与我的工程图表相同,其中志愿者和非营利组织是用户。我不想要聚合或组合,因为在我的 UML 志愿者中继承自用户。
我愿意接受建议,谢谢大家
正确的实现方式是不要有另一个主键。实现如下所示:
public class User
{
[Key]
public int UserId { get; set; }
public string Email{ get; set; }
public string Password { get; set; }
}
[Table("Volunteer")]
public class Volunteer : User
{
public DateTime BirthDate { get; set; }
}
[Table("NonProfit")]
public class NonProfit: User
{
public string Address { get; set; }
}
public class MyContext: DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Volunteer> Volunteers { get; set; }
public DbSet<NonProfit> NonProfits { get; set; }
}
有关更多信息,请查看这篇文章:http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type