【问题标题】:Entity framework doesn't generate JsonIgnoreAttribute实体框架不生成 JsonIgnoreAttribute
【发布时间】:2012-09-23 22:56:45
【问题描述】:

我正在尝试从实体框架 4 edmx 生成的 MVC 4 web api ApiController 对象返回,并带有 accept:json/application。

问题是 json 格式化程序还返回导航属性,我不想返回(我只想返回原始属性)。

所以我查看了生成的实体框架 4 代码,在导航属性中,只有 XmlIgnoreAttribute 和 SoapIgnoreAttribute 而我需要 JsonIgnoreAttribute。

我无法更改生成的代码,因为它将在下次更改 edmx 时被覆盖, 那么如何配置使用 JsonIgnoreAttribute 生成模型生成?

谢谢

【问题讨论】:

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


    【解决方案1】:

    虽然我不知道这是错误还是不受支持的功能,但我建议您定义视图模型并让 API 控制器操作返回视图模型,而不是 EF 自动生成的域模型。视图模型显然只包含您想要公开的属性。单个视图模型可以表示多个域模型的聚合。所以不要依赖任何 XmlIgnore、SoapIgnore、JsonIgnore、... 属性。依靠您的视图模型。

    【讨论】:

    • 是的!实体并不真正适合序列化和其他类型的传输。
    【解决方案2】:

    好的,我知道该怎么做了。 我们需要这样使用自定义的 DefaultContractResolver:

    public class ExcludeEntityKeyContractResolver : DefaultContractResolver
    {
        private static Type mCollectionType = typeof(System.Data.Objects.DataClasses.RelatedEnd);
    
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var members = GetSerializableMembers(type);
    
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
            IList<JsonProperty> serializeProperties = new List<JsonProperty>();
    
            for (int i = 0; i < properties.Count; i++)
            {
                var memberInfo = members.Find(p => p.Name == properties[i].PropertyName);
                if (!memberInfo.GetCustomAttributes(false).Any(a => a is SoapIgnoreAttribute) && properties[i].PropertyType != typeof(System.Data.EntityKey))
                {
                    serializeProperties.Add(properties[i]);
                }
            }
            return serializeProperties;
        }
    }
    

    在 Global.asax 中:

            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
            serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver();
            var jsonMediaTypeFormatter = new JsonMediaTypeFormatter();
            jsonMediaTypeFormatter.SerializerSettings = serializerSettings;
            GlobalConfiguration.Configuration.Formatters.Insert(0, jsonMediaTypeFormatter);
    

    不用担心性能,因为在整个应用程序持续时间内,每种类型只会调用一次 CreateProperties :)

    【讨论】:

    • 正是我想要的。感谢您提供此解决方案。在大多数情况下,对我的项目而言,为 DTO 精心创建模型是浪费时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多