Serialize one to many relationships in Json.net

后端 未结 5 535
盖世英雄少女心
盖世英雄少女心 2020-12-08 08:44

I am using the Entity Framework code first for data access and I have a Company class which has a collection of Employees. The Employee class also has a Company property.

5条回答
  •  囚心锁ツ
    2020-12-08 09:06

    In case this helps anyone, I thought I'd document how we resolved this same error for our purposes when using Entity Framework 4.3.1 and JSON.Net 4.5.3.

    We are using the Database First DbContext approach. For our needs, we could resolve it using the [JsonIgnore] attribute. The trick is just that since changes to the automatically generated entity classes are overwritten when you refresh from the database, with Database First you can add the attributes using the "metadata buddy class" approach given in this StackOverflow post.

    Below is a code excerpt. We had a "Query" object (class Query) that had relationships to "Company" and "User" objects. In a new class file, we declare the partial class with a [MetadataType] attribute, and then in the QueryMetadata class we specified, we annotate the members we want to ignore— namely the public virtual members that EF4.x adds to express the relationships (a.k.a. navigation properties).

    The Query entity also has foreign key fields (named FK_User and FK_Company in our case). These fields do not need the [JsonIgnore] attribute— they can be serialized with their foreign key values.

    [MetadataType(typeof(QueryMetadata))]
    public partial class Query
    {
    }
    
    
    public class QueryMetadata
    {
        [JsonIgnore]
        public virtual Company company { get; set; }
        [JsonIgnore]
        public virtual User user { get; set; }
    }
    

    However, if we actually had to also serialize the related Company or User objects, we'd hit a brick wall! The approach suggested by John Bubriski here wouldn't work for us since we want to rely on Entity Framework change tracking.

提交回复
热议问题