避免循环引用提供过多数据

时间:2012-12-20 22:10:42

标签: json asp.net-web-api entity-framework-ctp5

我遵循了所有程序,以避免在我的Wines / Vineyard项目中进行循环引用。但是我得到了我不想要的数据:

enter image description here

我不希望每一个附属葡萄园的葡萄酒上市,每次葡萄园每个葡萄酒列出时,葡萄园都会列出每一款葡萄酒。我怎么能阻止这个?我不想做匿名类型。

更新

我的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();

1 个答案:

答案 0 :(得分:0)

您如何序列化数据?

只是不要序列化您的wines集合属性。根据您的序列化机制,您可以使用属性(即ScriptIgnore)标记它或定义具体类型(因为您不喜欢匿名类型)并使用AutoMapper来复制数据。

将EF实体直接绑定到API的响应并不是最佳设计选择。每次修改db模式时,API都会发生变化。您可以定义API控制器将返回的单独类,并使用AutoMapper复制数据。这样您就可以将数据库架构与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
相关问题