使用 Entity Framework 返回 JsonResult 时循环引用的避免。
发表时间: 2011-03-23 06:29:17 | 评论: 3 | 查看: 340 | 来自: LUKIYA_NEVERLAND
最近在做公司的一个Dealer WHOLE SALE系统,使用了Entity Framework MVC3,在返回JsonResult时遇到了循环引用的问题。
刚开始使用 [ScriptIgnore] 来避免此问题,可是发现Designer.cs改动时会把这个属性给自动删除,继续查阅了很多资料,自定义了一个JavaScriptConverter解决了问题,下面是代码。
public class EFJavaScriptConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
IDictionary<string, object> result = new Dictionary<string, object>();
//
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
bool allowSerialize = IsAllowSerialize(property);
if (allowSerialize)
{
result[property.Name] = property.GetValue(obj, null);
}
}
//
return result;
}
private bool IsAllowSerialize(PropertyInfo property)
{
object[] attrs = property.GetCustomAttributes(true);
foreach (object attr in attrs)
{
if (attr is System.Data.Objects.DataClasses.EdmScalarPropertyAttribute)
{
return true;
}
}
//
return false;
}
public override IEnumerable<Type> SupportedTypes
{
get
{
yield return typeof(System.Data.Objects.DataClasses.EntityObject);
}
}
}
使用方法:
IList<OLX_Users> list = _MembershipService.GetUsers();
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.RegisterConverters(new List<EFJavaScriptConverter>() { new EFJavaScriptConverter() });
string content = js.Serialize(list);
return new ContentResult { Content = content, ContentType = "application/json" };
浙公网安备 33010602011771号