使用实体框架处理自定义字段

cli*_*uke 2 c# asp.net-mvc entity-framework ef-code-first asp.net-mvc-4

目前我有一个项目需要处理具有用户可以指定的自定义字段的产品。

有谁知道使用模型和代码优先注释实现此目的的最佳方法是什么?

我想在数据库方面,我需要一个新表来处理链接到 ProductID 的自定义数据。

emr*_*azi 5

您可以为用户可以添加的自定义属性指定单独的表。此自定义字段将引用您的主模型。基本上你们会有1 to M关系

public class MyModel
{
    public int MyModelID            { get; set; }

    public string FixedProperty1    { get; set; }
    public string FixedProperty2    { get; set; }

    // This is a navigation property for all your custom properties
    public virtual ICollection<CustomProperty> CustomProperties  { get; set; }
}

public class CustomProperty
{
    public int CustomPropertyID      { get; set; }

    // This is the name of custom field
    public string PropertyName       { get; set; }
    // And this is its value
    public string PropertyValue      { get; set; }

    // FK reference and navigation property to your main table
    public int MyModelID             { get; set; }
    public virtual MyModel MyModel   { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 虚拟在 EF 上下文中具有不同的含义。它提供延迟加载。基本上,当您从数据库获取 MyModel 时,除非您明确请求,否则它不会附带自定义属性。如果您认为大多数时候都需要模型本身的自定义属性,则可以安全地删除 virtual 关键字。更多信息请点击这里。http://stackoverflow.com/questions/5597760/what-effects-can-the-virtual-keyword-have-in-entity-framework-4-1-poco-code-fi (3认同)