Search code examples
c#entity-frameworkpropertiesfluentderived-class

Entity framework adding properties to my class (over my head)


I'm trying to create a datastructure with entity framework to basically store property values of my objects. I want users to add properties to a class at runtime. The properties can be of different datatypes. (string/int/float etc..)

So I thought I needed some tables/classes as defined in the image below. Tables So my Object class contains a list of properties that are of a type defined in de propertydefinition class.

One hard thing is that values are stored in the table of the datatype of the propertie. (So a conditional foreignKey?)

Please give me some pointers on how to implement this by using Fluent API. Or other ideas on this subject. (I guess I won't be the first ;)

Werner


Solution

  • I found this link

    This helped me solve my "Table Per Type" question. I now have:

    public abstract class PropertyBase
    {
        public int PropertyID { get; set; }
        public string Name { get; set; }
    }
    
    public class TextProperty : PropertyBase
    {
        public string Value { get; set; }
    }
    
    public class IntProperty : PropertyBase
    {      
        public int Value { get; set; }
    }
    

    In My Database Context I added:

            modelBuilder.Entity<PropertyBase>()
                .HasKey(p => p.PropertyID)
                .ToTable("Properties");                    
    
            modelBuilder.Entity<IntProperty>()
                .ToTable("IntProperties");
    
            modelBuilder.Entity<TextProperty>()
                .ToTable("TextProperties");
    

    The different types of properties (sub classes) are now stored in separate tables. The main abstract class contains all the other info. This worked fine for me.