【问题标题】:Create Fields dynamically using Entity Framework使用实体框架动态创建字段
【发布时间】:2013-03-15 08:35:16
【问题描述】:

我正在开发一个 CMS,我有一个这样的类别:

public partial class Category
{
   public int CategoryId {get;set;}
   public string CategoryName {get;set;}
   public string CategoryType {get;set;}
}

我正在使用 Entity Framework 在我的数据库中存储和创建这样的数据库表。现在,如何将动态字段添加到此模型并因此添加到数据库中。我允许用户添加他想要添加的自定义字段。 所以,我的数据库架构变成了

Category(CategoryId, CategoryName, CategoryType, CustomField1, CustomField2);

如何使用 EF 5 做到这一点?

【问题讨论】:

    标签: asp.net-mvc database asp.net-mvc-4 content-management-system entity-framework-5


    【解决方案1】:

    你不能以你期望的方式。而不是将自定义字段添加到Category 表,您需要类似CategoryExtension 表,您将在其中存储CategoryIdFieldNameFieldValue(与特定类别记录相关的键值对)其中CategoryId 将是FK 到Category 表,例如CategoryIdFieldName 将构建复合PK。您的课程将如下所示:

    public partial class Category
    {
       public int CategoryId {get;set;}
       public string CategoryName {get;set;}
       public string CategoryType {get;set;}
       public virtual ICollection<CategoryExtension> Extensions { get; set; }
    }
    
    public class CategoryExtension 
    {
       public int CategoryId { get; set; }
       public string Name { get; set; }
       public string Value { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-29
      • 2016-05-22
      • 2011-07-15
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多