【问题标题】:How to add database field in table dynamically using MVC and Entity Framework using .Net?如何使用 MVC 和使用 .Net 的实体框架在表中动态添加数据库字段?
【发布时间】:2014-05-06 12:26:56
【问题描述】:

我正在开发一个 .Net 应用程序,并且我有可用的数据库。 我有一个类别类:

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

如何将动态字段添加到此模型并因此添加到数据库?如果不可能,还有其他方法可以解决我的问题吗?

我允许用户添加他想要添加的自定义字段。所以,我的数据库架构变成了

Category(CategoryId, CategoryName, CustomField1, CustomField2);

如何使用 EF 5 和 MVC 做到这一点?或者我们还有其他方法可以做到吗?

【问题讨论】:

  • 您能否详细说明为什么要动态添加这些自定义字段?我认为可能有比像这样动态添加数据库字段更好的方法来实现这一点。
  • 您需要在运行时(不知何故)重新编译在添加字段后加载 EF 模型的整个托管模块。这可能是可能的,但完全不切实际。
  • 我建议在您的Category 类中添加一个列表,这就像一个名为CustomField 的对象列表,只需在该列表中添加更多。因此,在您的数据库中,您将有一个与 Category 相关的 CustomFields
  • 这不是正确的方法(有问题的想法)
  • 我想为用户提供添加一些自定义字段的功能,例如 vTiger (vtiger.com) 应用程序。我已经展示了一些 CRM 工具让用户可以即时将自定义字段添加到数据库并显示在添加/编辑和列表页面上。例如。我们有一个产品模块,在模块中我们只提供以下字段 1. 产品名称 2. 产品类型 3. 产品价格 现在用户想根据需要在产品模块中添加另一个字段,如 1. 产品类别 2. 产品描述

标签: c# asp.net-mvc database entity-framework model-view-controller


【解决方案1】:

将添加此建议作为答案,因为我认为动态向数据库添加列不是最好的主意。

在您的Category 类中,添加另一种类型的列表,我们称之为CustomField。当您允许用户添加新字段时,只需将其粘贴到此列表中即可

public partial class Category
{
   public int CategoryId {get;set;}
   public string CategoryName {get;set;}
   public IList<CustomField> CustomFields {get;set;}
}

public class CustomField
{
   public int CustomFieldId {get;set;}

   public string FieldName {get;set;}
   public string FieldValue {get;set;}

   [ForeignKey("Category")]
   public int CategoryId {get;set;}
   public Category Category {get;set;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2013-03-15
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多