好的,我發現該怎麼做。 我們需要這樣的定製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精心創建模型是浪費時間。 – TaeKwonJoe