简体   繁体   English

Json反序列化数据库字段和asp.net MVC

[英]Json deserialization of database field and asp.net mvc

Let say I have general table of records (I'm using EF code first) and there can be many different types of details that can be used with this table: 假设我有一个通用的记录表(我先使用EF代码),并且该表可以使用许多不同类型的详细信息:

class Record{
int Id,
int TypeOfDetails, // int enum Type1, Type2
string Details, //string with json content
string Attribute 1,
string Atribute 2,
...
}

class DetailsType1{
  string InternalAtribute1,
  ....
}

I decided to use Json to serialize Details objects into database field. 我决定使用Json将Details对象序列化为数据库字段。 This allows to flexible work with different Details without changing DB schema. 这允许在不更改数据库架构的情况下灵活地处理不同的详细信息。

Working with one records is easy, I know type of the Details object, so I can serialize and deserialize. 我知道一个Details对象的类型,因此使用一条记录很容易,因此我可以序列化和反序列化。

But how to efficiently retrieve multiple records and be able to reference details in in MVC ? 但是如何有效地检索多个记录并能够在MVC中引用详细信息? Let say I do this: 可以说我这样做:

var results = await context.Record.Where(..).ToAsyncList();

I would want to be able to do this in my .cshtml: 我希望能够在我的.cshtml中执行此操作:

@Html.DisplayFor(modelItem => item.Record.Details.InternalAtribute1)

Essentially it would be doing deserialization on the fly.. 从本质上讲,它将进行即时反序列化。

Alternatively if something like that is possible in AngularJS it would also be helpful. 另外,如果在AngularJS中可以进行类似的操作,它也会有所帮助。

Let me know if I make myself clear with my question. 让我知道我是否清楚自己的问题。

I will answer my questions. 我会回答我的问题。 The best I figure out was this: 我认为最好的是:

    class Record{
    int Id { get; set; }
    int TypeOfDetails { get; set; } // int enum Type1, Type2
    string JsonDetails { get; set; } //string with json content
    string Attribute1 { get; set; }
    string Atribute2 { get; set; }
    ...
    [NotMapped]
    public JObject Details { get; set; }

    public void PopulateDetails()
    {
        Details = JObject.Parse(JsonDetails);
    }    
}

You still need to execute PopulateDetails on all query results, I'm doing it in foreach loop. 您仍然需要在所有查询结果上执行PopulateDetails,我正在foreach循环中执行。 Then in CSHTML you can do this: 然后,在CSHTML中,您可以执行以下操作:

@item.Details["InternalAtribute1"])

Your internal Json object's details can be displayed. 可以显示内部Json对象的详细信息。

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

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