Projecting self referencing multi level Entities In Entity Framework 6

后端 未结 2 1729
感情败类
感情败类 2021-01-14 02:48

Projecting self referencing multi level entities in Entity Framework 6.

Let\'s say that I have a Category entity as follows:

public clas         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 03:32

    It might not be elegant, but a suitable solution is to have in your code a shared IDictionary. When you are going to map an entity Category into a CategoryView check first if you have already created this object and set the reference stored in the dictionary instead of creating a CategoryView instance. When creating a new instance, store it in the dictionary. This is a way to take advantage of the primary key of your entity to avoid the infinite recursion issue in your code.

    Also, notice that in your CategoryView object you shouldn't be referencing Category instances. Update it to reference CategoryView instances like this.

    public class CategoryView
    {
    
        public int Id { get; set; }
    
        public int? ParentCategoryId { get; set; }        
    
        // other properties ...
    
        public CategoryView ParentCategory { get; set; }
    
        public List SubCategories { get; set; }
    
        public int ProductCount { get; set; }
    
        public CategoryView()
        {            
            SubCategories = new List();
        }
    }
    

提交回复
热议问题