C#ASP.Net MVC动态对象属性 [英] C# ASP.Net MVC dynamic object properties

查看:184
本文介绍了C#ASP.Net MVC动态对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C#进行 ASP.NET MVC 项目。首先是EF 代码。

I am working on a ASP.NET MVC project, with C#, and EF code first.

我需要为实体添加动态属性。例如-

I am required to add dynamic properties to entities. For example -

我有一辆汽车作为基础对象。我可以为其添加自定义属性,例如引擎功率,长度,颜色等。

I have a car as a base object. I can add custom properties for it like engine power, length, color etc etc.

属性可以是布尔值,整数,字符串或选择选项(即,我必须创建复选框,当用户输入这些属性的值时输入或选择html元素。)

Properties can be boolean, int, string or select options (ie, i have to create checkbox, input or select html elements when a user inputs values for those properties).

属性必须具有自定义验证规则(即,必填,仅数字,仅范围等) 。

Properties must have custom validation rules (i.e., required, number only, range only etc).

你们能给我任何线索或指导来实现这一目标吗?

Can you guys give me any clues or direction how to accomplish this?

谢谢

推荐答案

如果您真正拥有动态属性,则由于EF6假定有关系数据库,因此您将无法(直接)使用EF6。

If you truly have dynamic properties you won't be able to do this (directly) with EF6 since EF6 assumes a relation database. and a relational database needs to know which columns to expect.

现在您有2个选项。

选项1:
使用带有EF 7的非关系数据库。您可以在此处查看 https ://msdn.microsoft.com/zh-cn/magazine/dn890367.aspx 了解有关EF7的更多详细信息,但基本上,在非关系数据库中,您可以存储任何json blob-动态属性也可以存储

Option1: use a non-relational database with EF 7. you can look here https://msdn.microsoft.com/en-us/magazine/dn890367.aspx for some more details about EF7 but basically in a non relation database you can store any json blob - so also your dynamic properties

选项2:在对象中使用键值对。并存储这些属性

Option 2: Use a key value pair within your object. and store those properties

class KeyValuePair {
   int Id {get; set;}
   string name {get; set;}
   string stringValue {get; set;}

}

class BaseObject {

    int Id {get; set;}
    list<KeyValuePair> dynamicProperties {get; set;}

}

现在您的汽车可以从该基础对象继承了。您仍然需要完成创建KeyValuePair对象的工作。 (如果要存储字符串,整数等,则可以创建不同的KeyValuePair类型,每种存储类型都可以使用一种)。

Now your car can just inherit from this baseobject. You still need to do the work to create your KeyValuePair objects. (And if you want to store strings, ints etc you can make Different KeyValuePair types, one for each storage type)

尽管使用诸如

更新:

如果要验证动态对象,例如这就是您要实现IValidatableObject

If you want to validate a dynamic object like this you want to implement IValidatableObject

的结果,所以您获得

 class Car: BaseObject, IValidatableObject {
      public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        /* code to validate your properties here, for example you need at least 1 engine, 4 wheels etc */

        yield return ValidationResult.Success;
    }
 }

这篇关于C#ASP.Net MVC动态对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆