2

Currently I have a project that needs to handle products with custom fields that the users can specify.

Does anyone know what the best way to implement this using Models and Code First Annotations?

I figured on the database side, I will need a new table to handle custom data that will be linked to the productID.

clifford.duke
  • 3,980
  • 10
  • 38
  • 63

1 Answers1

5

You can specify a seperate table for custom properties that your users can add. This custom field will have a reference to your main model. Basically, you will have 1 to M relationship

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; }
}
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
  • 1
    What is the purpose of specifying it as a `virtual` function? – clifford.duke May 29 '13 at 08:56
  • 3
    Virtual have different meaning in EF context. It provides lazy loading. Basically, when you fetch the MyModel from db, it wont bring the custom properties with it unless you request it explicitly. If you believe you will need the custom properties with model itself most of the time, you can safely remove virtual keyword. More info here. http://stackoverflow.com/questions/5597760/what-effects-can-the-virtual-keyword-have-in-entity-framework-4-1-poco-code-fi – emre nevayeshirazi May 29 '13 at 08:58
  • Oh okay, I know about lazy loading from my experience with Doctrine, I didn't realize that using `virtual` is how you handle that for EF. Thanks a lot for the information! – clifford.duke May 29 '13 at 09:05
  • You snow only strings their but wjat if u nedded other values like infs decimal – c-sharp-and-swiftui-devni Oct 22 '22 at 16:44