简体   繁体   English

实体框架向我的班级添加属性(头顶)

[英]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. 所以我认为我需要一些图片中定义的表/类。 桌子 So my Object class contains a list of properties that are of a type defined in de propertydefinition class. 因此,我的Object类包含一个属性列表,这些属性属于de propertydefinition类中定义的类型。

One hard thing is that values are stored in the table of the datatype of the propertie. 一件难事是,值存储在属性数据类型的表中。 (So a conditional foreignKey?) (因此,有条件的foreignKey?)

Please give me some pointers on how to implement this by using Fluent API. 请给我一些有关如何使用Fluent API实施此操作的指示。 Or other ideas on this subject. 或关于此主题的其他想法。 (I guess I won't be the first ;) (我想我不会是第一个;)

Werner 维尔纳

The EF entity model cannot be changed during Runtime (or at least is not designed for). EF实体模型不能在运行时更改(或至少不是为运行而设计的)。 You could use an infrastructure to store propertyname/propertyvalye with EF but I think is not the right choice (you lose most of the functionalities). 您可以使用基础结构将属性名称/ propertyvalye与EF一起存储,但是我认为这不是正确的选择(您失去了大多数功能)。

The best choice could be a NoSQL db, ADO.Net or, if only some objects can be personalized and other are fixed you could store the personalizable objects in XML/JSON in a text field. 最好的选择可能是NoSQL db,ADO.Net,或者,如果仅某些对象可以被个性化而其他对象是固定的,则可以在文本字段中以XML / JSON存储个性化对象。

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. 这对我来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM