c# - Entity Framework Core 2.1 中的多级模型类

标签 c# asp.net database entity-framework-core

我的数据库实体项目有大约 30 列,我想创建清晰的 EF Core 模型,其中许多列分为几个类。

例如,覆盖实体是Sensors,它有两个元素(Int ID,ElectricalData electricData)ElectricalData是一个单独的类,接下来有 ​​3 个独立的类和两个 boolstring 对象。

Add-Migration过程中以这种方式构建的模型返回子实体没有主键的反馈,但它们不应该包含PK,因为只有Sensors 类应该有一个主键。

如何解决这个问题?这个想法正确吗?

代码如下:

    public class SensorModel
    {
       [Key]
       public int ID { get; set; }
       public ElectricalDataModel ElectricalData { get; set; }
    }

   public class ElectricalDataModel
   {
      public TensionModel Tension { get; set; }
      public CurrentModel Current { get; set; }
      public string SecurityClass { get; set; }
      public ResistanceModel Resistance { get; set; }
      public bool ReversePolarizationSecurity { get; set; }
   }

   public class TensionModel
   {
      public double Minimum { get; set; }
      public double Maximum { get; set; }
      public string Current { get; set; }
   }
   //.......................................... and so on

最佳答案

你问的是什么叫Complex Types ,EF Core 术语为 Owned Entity Types 。默认情况下,它们与所有者共享同一个表,并用于在逻辑上分隔(分组)相关属性 - 正是您所描述的目标。

在 EF Core 2.1 中将类标识为自有类型的最简单方法是使用 OwnedAttribute 对其进行标记:

[Owned]
public class ElectricalDataModel
{
    // Properties..
}

[Owned]
public class TensionModel
{
    // Properties..
}

//.......................................... and so on

当然,通过 OwnsOne Fluent API 也可以实现同样的目的,它还允许您为每个所有者的拥有实体配置列名称和其他属性。

关于c# - Entity Framework Core 2.1 中的多级模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50988057/

相关文章:

C# 从 backgroundworker 连续更新 GUI

c# - 使用 WMI 调用解决 "Access Denied"异常

HTML 将元素放在同一行

php - Xampp Phpmyadmin 停止工作

c# - 添加声音过滤器并连接声音针脚

c# - 3 灵活的父 div 内的灵活 div

asp.net - asp mvc http get action 以对象为参数

asp.net - 在页面中显示 .Net 页面

python - MySQLdb 和使用 CursorUseResultMixIn 的大查询

mysql - 从Google图像中提取图像