1

我試圖從MVC 4 web api返回ApiController對象從實體框架4 edmx生成,接受:json /應用程序。實體框架不生成JsonIgnoreAttribute

問題是json格式化程序返回導航屬性,我不想返回(我只想返回原始屬性)。

所以我查看了實體框架4生成的代碼,在導航屬性中,只有XmlIgnoreAttribute和SoapIgnoreAttribute,而我需要JsonIgnoreAttribute。

我無法更改生成的代碼,因爲它會在edmx的下一次更改中被覆蓋,因此如何配置使用JsonIgnoreAttribute生成模型代?

謝謝

回答

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僅會被每一個類型稱爲整個申請期限:)

+0

正是我在找的東西。感謝這個解決方案。對於我的項目而言,在大多數情況下爲DTO精心創建模型是浪費時間。 – TaeKwonJoe

3

雖然我不知道這是否是一個錯誤或不支持的功能,我建議你定義視圖模型,有你的API控制器動作返回,而不是你的自動生成的EF域模型視圖模型。視圖模型顯然只包含您想要公開的屬性。單視圖模型可以表示多個域模型的聚合。所以不要依賴任何XmlIgnore,SoapIgnore,JsonIgnore,...屬性。依靠您的視圖模型。

+2

是的!實體並不適合序列化和其他類型的傳輸。 – usr