避免循环引用提供过多数据 [英] Avoiding Circular referencing providing too much data

查看:141
本文介绍了避免循环引用提供过多数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了所有程序,以避免在我的Wines/Vineyard项目中进行循环引用.但是我正在获取不需要的数据:

I followed all the procedures to avoid circular referencing in my Wines/Vineyard project. But I am getting data I do not want:

我不希望每一个拥有附属葡萄园的葡萄酒清单都让该葡萄园列出每一种葡萄酒.我该如何阻止呢?我不想做匿名类型.

更新:

我的DbContext:

My DbContext:

    public DataContext()
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

我的路线配置:

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

我的控制器:

var response = context.Wines.Include("Vineyard").ToList();

var response = context.Wines.Include("Vineyard").ToList();

推荐答案

如何序列化数据?

仅不要序列化您的wines集合属性.根据您的序列化机制,您可以使用属性(即ScriptIgnore)对其进行标记,也可以定义具体类型(因为您不喜欢匿名类型)并使用AutoMapper复制数据.

Just don't serialize your wines collection property. Depending on your serialization mechanism you can either mark it with an attribute (ie. ScriptIgnore) or define concrete types (since you don't like anonymous types) and use AutoMapper to copy data.

将EF实体直接绑定到API的响应不是最佳的设计选择.每次您修改数据库架构时,您的API都会更改.您可以定义API控制器将返回的单独类,并使用AutoMapper复制数据.这样,您就可以将数据库架构与API分离.

Binding your EF entities directly to the response of the API is not the best design choice. Every time you modify your db schema your API will change. You could define separate classes that your API controllers will return and use AutoMapper to copy data. That way you decouple your DB schema from your API.

namespace API {
    class Wine {
        // properties that you want to return goes here
    }
}

Mapper.CreateMap<Wine, API.Wine>(); // Only once during app start
Mapper.Map<Wine, API.Wine>(wine); // AutoMapper will copy data using conventions

这篇关于避免循环引用提供过多数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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