【问题标题】:Handling Custom Fields using the Entity Framework使用实体框架处理自定义字段
【发布时间】:2013-05-29 08:10:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-4 ef-code-first


    【解决方案1】:

    您可以为用户可以添加的自定义属性指定单独的表格。此自定义字段将引用您的主模型。基本上,您将拥有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; }
    }
    

    【讨论】:

    • 指定为virtual函数的目的是什么?
    • 虚拟在 EF 上下文中具有不同的含义。它提供延迟加载。基本上,当您从 db 获取 MyModel 时,除非您明确请求,否则它不会带来自定义属性。如果您认为大部分时间都需要模型本身的自定义属性,您可以安全地删除 virtual 关键字。更多信息在这里。 stackoverflow.com/questions/5597760/…
    • 哦,好吧,我从 Doctrine 的经验中知道延迟加载,我没有意识到使用 virtual 是你处理 EF 的方式。非常感谢您提供的信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多