c# - 在 edmx 中生成的类中带有外键的表缺少成员

标签 c# entity-framework foreign-keys entity-framework-6 ef-database-first

我在数据库中有一个表,有 4 个外键引用它。当我将表格添加到 edmx 时,表格和导航属性就在那里。但是,该表中的外键 ID 丢失了,只有虚拟对象在那里。

这是在 .tt 文件中生成的下表:

public partial class Device
{
    public int SolutionId { get; set; }
    public string SiteId { get; set; }
    public string Name { get; set; }
    public int SysId { get; set; }
    public Nullable<int> SysType { get; set; }
    public string SerialNumber { get; set; }
    public Nullable<int> ParentId { get; set; }

    public virtual DeviceModel DeviceModel { get; set; }
    public virtual DeviceType DeviceType { get; set; }
    public virtual SolutionApplication SolutionApplication { get; set; }
    public virtual SolutionType SolutionType { get; set; }
}

缺少一些成员:

DeviceModelId, DeviceTypeId, SolutionApplicationId, and SolutionTypeId

为什么不见了?有没有办法让这些键实际上成为部分类的一部分?

使用 EntityFrameworks v6.0.2。延迟加载

最佳答案

简而言之, Entity Framework “将其抽象化”。

它足够聪明,可以识别您的 FK 代表关系,因此您可以使用对象本身。因此,您不必担心检查 FK 约束等,例如 SolutionTypeId - 您只需将 SolutionType 对象添加到您的 Device 对象并让 Entity Framework梳理出来。 (当然,如果您尝试添加违反 SolutionType PK 的新 SolutionType,这会导致问题,因此您可能需要先从 SolutionTypes 表中找到一个现有对象)。

因此,与其将其视为通过 FK 链接到 SolutionType 表的 Device 表,不如将其视为 DeviceSolutionType 对象作为属性的对象。当您保存更改时,EF 会为您整理数据库(假设您的模型是准确的!)

关于c# - 在 edmx 中生成的类中带有外键的表缺少成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637300/

相关文章:

php - MySQL 外键..困惑

c# - 如果类是对象的蓝图,那么静态类呢?

c# - 如何获取程序集的完整文件路径?

.net - 在 Entity Framework 5 中将代码生成从无更改为默认值后出现错误

c# - 连接来自 IQueryable 和 IList<KeyValuePair> 的数据

python - 我可以使用触发器来添加外键组合吗?

c# - 防止相机离开地形

c# - 使用 async-await 可以给您带来任何性能优势吗?

c# - Entity Framework 更新未保存

mysql - 我们所有的 MySQL 约束都变成了小写。什么会导致这种情况?