将[JsonIgnore]应用于属性会导致DataAnnotation属性“丢失". [英] Applying [JsonIgnore] to property causes DataAnnotation attributes to be "lost"

查看:148
本文介绍了将[JsonIgnore]应用于属性会导致DataAnnotation属性“丢失".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

    [JsonIgnore]
    [Display(Name = "Loan Cap")]
    public virtual string SomeProperty { get; protected set; }

当ASP.NET MVC调用DataAnnotationsModelMetadataProvider.CreateMetadata来完成以下调用时:

When the DataAnnotationsModelMetadataProvider.CreateMetadata is called by ASP.NET MVC to fulfil the following call:

@Html.DisplayNameFor(model => model.SomeAttribute)

传递给CreateMetadata的属性列表不包括[Display]属性(或与此相关的[JsonIgnore]).如果删除[JsonIgnore],则会找到[显示]并将其传递给CreateMetadata.有人知道为什么会这样吗?

The list of attributes handed to CreateMetadata does not include the [Display] attribute (or the [JsonIgnore] for that matter). If I remove the [JsonIgnore] then the [Display] gets found and passed to CreateMetadata. Anyone have any idea why this is happening?

推荐答案

这似乎是较旧版本的Newtonsoft.Json nuget程序包中的错误/问题.
我确认该软件包的版本9.0.1中存在该问题

This seems to be a bug/issue in older versions of the Newtonsoft.Json nuget package.
I confirmed the issue exists in version 9.0.1 of the package

此问题已在版本10.0.1中修复

就我而言,我正在执行的Entity Framework迁移正在等待更改时发生更改错误,但不是从Package Manager Console中进行.我发现这是因为相同的问题,导致所有属性丢失"的JsonIgnore属性仍然出现.控制台命令"Update-Database"和"Add-Migration"仍然看到ForeignKey属性.但是,如果代码正在执行,则Entity Framework不会看到ForeignKey属性,而会引发未决的更改迁移错误.

In my case, I was getting Entity Framework migration pending changes errors when executing, but not from Package Manager Console. I discovered that this is because of this same issue, the JsonIgnore attribute causing all attributes to be "lost" The console commands, "Update-Database" and "Add-Migration" still saw a ForeignKey attribute. But if the code was executing, Entity Framework didn't see the ForeignKey attribute and threw a pending changes migration error.

这篇关于将[JsonIgnore]应用于属性会导致DataAnnotation属性“丢失".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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