自己寫實體可以完美解決這個問題。 用匿名類型也可以。 設置上下文方法如下: (jz為資料庫上下文對象) jz.Configuration.ProxyCreationEnabled = false;jz.Configuration.LazyLoadingEnabled = false; 不用這個的原因 ...
自己寫實體可以完美解決這個問題。
用匿名類型也可以。
設置上下文方法如下:
(jz為資料庫上下文對象)
jz.Configuration.ProxyCreationEnabled = false;
jz.Configuration.LazyLoadingEnabled = false;
不用這個的原因是Virtual屬性也會生成。(只是占個位,[]裡面沒內容,但看著不爽)
我採用的方法是過濾掉Virtual屬性的方法:
一個基於Json.net的類
public class LimitPropsContractResolver : DefaultContractResolver { string[] props = null; bool retain; /// <summary> /// 構造函數 /// </summary> /// <param name="props">傳入的屬性數組</param> /// <param name="retain">true:表示props是需要保留的欄位 false:表示props是要排除的欄位</param> public LimitPropsContractResolver(string[] props, bool retain = true) { //指定要序列化屬性的清單 this.props = props; this.retain = retain; } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> list = base.CreateProperties(type, memberSerialization); //只保留清單有列出的屬性 return list.Where(p => { if (retain) { return props.Contains(p.PropertyName); } else { return !props.Contains(p.PropertyName); } }).ToList(); } public static string[] GetVirtualList<T>() { var stringType = typeof(T); var props = stringType.GetProperties(); List<string> test = new List<string>(); foreach (var prop in props) { if (prop.GetAccessors()[0].IsVirtual) { test.Add(prop.Name); } } return test.ToArray(); } }
和一個對PropertyInfo的擴展方法
public static class Virtual_Help { public static bool? IsVirtual(this PropertyInfo self) { if (self == null) throw new ArgumentNullException("self"); bool? found = null; foreach (MethodInfo method in self.GetAccessors()) { if (found.HasValue) { if (found.Value != method.IsVirtual) return null; } else { found = method.IsVirtual; } } return found; } }
使用方法如下
JsonSerializerSettings jsetting = new JsonSerializerSettings(); jsetting.ContractResolver = new LimitPropsContractResolver( LimitPropsContractResolver.GetVirtualList<affairs>(), false); string json = JsonConvert.SerializeObject(temp, Formatting.Indented, jsetting);