gpt4 book ai didi

.net - 具有不同键名的 Table-Per-Type 数据模型?

转载 作者:行者123 更新时间:2023-12-02 01:39:32 25 4
gpt4 key购买 nike

我有一个遗留数据库模式,我想用一个表类型的 Entity Framework 映射对其进行建模。然而,基表和子类表对主键使用不同的名称,而 EF 似乎不喜欢这样。

例如:

[Table("People")]
abstract class Person {
[Key, Column("Id")]
public int Id { get; set; }

// Person properties...
}

[Table("Employees")]
class Employee : Person {
[Key, Column("PersonId")]
public new int Id { get; set; }

// Employee-specific properties...
}

这确实有效,至少对于阅读而言: Employee映射到 People 中的记录表加上来自 Employees 的记录 table 。但是, Entity Framework 不会填充 Employee.Id (它总是零),所以我求助于注释 Employee.Id[Obsolete]以确保我的其余代码不会尝试使用它。

我担心使用 new以这种方式似乎是一个可怕的黑客。

有没有更惯用/正确的方法?

最佳答案

好的……我对此有一点解决方案……问题是,为基表和派生表上的主键声明不同键名的唯一方法是在派生类中再次声明键,并且 EF没有为派生类上的键设置值,所以:

[Table("Employees")]
class Employee : Person {
[Key, Column("PersonId")]
public new int Id {get{return base.Id;}set{base.Id=value;}}
}

在派生类中声明键,但将其委托(delegate)给基类中的键属性。当 Entity Framework 设置一个时,它会自动设置两者——这很好,因为根据定义它们必须相同。

关于.net - 具有不同键名的 Table-Per-Type 数据模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com