我有一个EF对象:
public class User
{
[Key, Column("userid", TypeName = "int")]
public Int32 UserId { get; set; }
[Column("username", TypeName = "varchar")]
public String UserName { get; set; }
[Column("password", TypeName = "varchar")]
public String Password { get; set; }
[Column("name", TypeName = "varchar")]
public String Name { get; set; }
[Column("surname", TypeName = "varchar")]
public String Surname { get; set; }
[Column("email", TypeName = "varchar")]
public String Email { get; set; }
[Column("dob", TypeName = "datetime")]
public Nullable<DateTime> Dob { get; set; }
[Column("notes", TypeName = "nvarchar")]
public String Notes { get; set; }
[Column("masterentity", TypeName = "varchar")]
public String MasterEntity { get; set; }
[Column("propertyid", TypeName = "int")]
public Nullable<Int32> PropertyId { get; set; }
[Column("boardmember", TypeName = "bit")]
public Boolean BoardMember { get; set; }
[Column("occupiesunit", TypeName = "bit")]
public Boolean OccupiesUnit { get; set; }
[Column("systemuser", TypeName = "bit")]
public Boolean SystemUser { get; set; }
[Column("isactive", TypeName = "bit")]
public Boolean IsActive { get; set; }
#region Foreing Keys
[ForeignKey("MasterEntity")]
public virtual Entity CurrentMasterEntity { get; set; }
#endregion
}
在客户端,我试图将模型序列化为像这样的JSON对象:
var jsonUser = @(Html.Raw(Json.Encode(this.Model)));
我收到以下错误:
A circular reference was detected while serializing an object of type ....
我意识到如果我删除 Foreing Keys Fluent API
[ForeignKey("MasterEntity")]
public virtual Entity CurrentMasterEntity { get; set; }
然后它完美无缺。所以似乎与其他实体有关系的实体或对象不能使用JSON序列化。
任何人都有解决这个问题的好方法吗? IS EF 5.0会解决这个问题吗?
非常感谢。
答案 0 :(得分:0)
只要在它们之间没有循环引用,就可以序列化具有关系的实体。这意味着如果您A
指向B
,而B
指向A
,则不会。我怀疑你的CurrentMasterEntity
将永远等于实体本身,或者可能存在循环图(A是B的主控,B是A的主控),所以你有一个数据错误或两个定向导航(通常以Entity Parent
和ICollection<Entity> Children
形式出现)。如果这是数据错误,请修复它。如果您有双向导航,则必须选择一个将被序列化的属性,并使用[ScriptIgnore]
标记其他属性,以便不会序列化。
但如果您在客户端确实不需要CurrentMasterEntity
,请使用前面提到的[ScriptIgnore]
进行标记。