【问题标题】:EF4.1 How to map List of properties from different tablesEF4.1 如何映射来自不同表的属性列表
【发布时间】:2012-02-10 11:36:38
【问题描述】:

假设我们有以下类:

public class MyEntity
{
   public Guid Id { get; set; }
   public int EntityType { get; set; }
   public List<integer> DataValues { get; set; }
}

表结构是这样的:

MyEntity
Id uniqueidentifier

我想根据 EntityType 将 DataValues 的值存储在不同的表中。例如,MyEntity1 将有两个整数字段,而 MyEntity2 可能有三个整数字段。

MyEntity1
EntityId (FK to MyEntity)
Integer1 int
Integer2 int

MyEntity2
EntityId (FK to MyEntity)
Integer1 int
Integer2 int
Integer3 int

因此,如果我有一个“MyEntity1”类型的实例,我的表将具有以下值:

MyEntity
Id          EntityType
---------------------
someguid1     1

MyEntity1
EntityId  Integer1   Integer2
------------------------------
someguid1 100         200

在运行时另一个类说 MyEntityDefinition 存储实体存储多少个整数,通过引用这个类我可以知道如果实体是 MyEntity1 类型,那么它包含两个整数值。

我想将此表结构映射到 MyEntity 类,有什么可能的方法吗?

PS:我不想定义类 MyEntity1、MyEntity2。我只是想用表结构(MyEntity、MyEntity1、MyEntity2)来存储数据。

基本上,我正在评估 EF 4.1 的场景,其中实体定义不固定且可由用户更新。有关实体的信息(元数据)存储在其他表中

【问题讨论】:

    标签: entity-framework-4.1 ef-code-first metadata dynamic-data


    【解决方案1】:

    不确定是否可行,但是像这样的事情怎么样:

    public class MyEntity
    {
       public Guid Id { get; set; }
       public int EntityType { get; set; }
    
       public static List<int> DataValues(MyEntity obj)
       {
          if (obj.EntityType == 1)
          {
             MyEntity1 e1 = (MyEntity1)obj;
             // TODO: return list of integers from e1
          }
       }
    }
    
    
    public class MyEntity1 : MyEntity
    {
      public int Integer1 {get;set;}
      public int Integer2 {get;set;}
    }
    

    【讨论】:

    • 如果使用多态会更好
    • 有趣的想法,但我不想定义类 MyEntity1、MyEntity2。我只想将我的数据存储在该表结构中
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-12-15
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    相关资源
    最近更新 更多