Skip to main content
 首页 » 编程设计

c#之使用 Entity Framework 处理自定义字段

2024年02月13日11jpfss

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

有谁知道使用模型和 Code First 注释实现此功能的最佳方法是什么?

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

请您参考如下方法:

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