我在数据库中有一个表,有 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
表,不如将其视为 Device
以 SolutionType
对象作为属性的对象。当您保存更改时,EF 会为您整理数据库(假设您的模型是准确的!)
关于c# - 在 edmx 中生成的类中带有外键的表缺少成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637300/