2011-10-19 68 views
0

我這樣定義無法序列化對象

public class Planilla 
{ 
    [Key] 
    public int IDPlanilla { get; set; } 

    [Required(ErrorMessage = "*")] 
    [Display(Name = "Dirección de Negocio")] 
    public int IDDireccionDeNegocio { get; set; } 

    [Required (ErrorMessage = "*")] 
    public string Nombre { get; set; } 
    [Display(Name = "Descripción")] 
    public string Descripcion { get; set; } 

    public bool Activo { get; set; } 

    [ScriptIgnore] 
    public virtual DireccionDeNegocio DireccionDeNegocio { get; set; } 
} 

一個模型,我在我的控制器的方法返回此模式的第一個元素

[HttpPost] 
    public ActionResult GetElements(string IDCampana) 
    { 
     Planilla query = db.Planillas.First(); 
     return Json(query);     
    } 

是我的問題,當我從客戶端調用此方法會拋出一個錯誤,說的是

檢測到循環引用嘗試序列化 System.Data.Entity.DynamicProxies.Planilla_7F7D4D6D9AD7AEDCC59865F32D5D02B4023989FC7178D7698895D2CA59F26FEE Debugging my code I realized that the object returned by the execution of the method首先it's a {System.Data.Entity.DynamicProxies.Planilla_7F7D4D6D9AD7AEDCC59865F32D5D02B4023989FC7178D7698895D2CA59F26FEE} instead a Model of my namespace like Example.Models.DireccionDeNegocio`。

爲什麼我做錯了?因爲我嘗試過使用其他模型和工作的好

+0

你能提供一個測試片段來突出你的錯誤嗎? –

回答

3

使用視圖模型,這是我可以給你的唯一建議。切勿將域模型傳遞給您的視圖。就這麼簡單。如果你尊重這個簡單的規則和ASP.NET MVC應用程序的基本規則,你永遠不會有問題。因此,舉例來說,如果你只需要id和視圖中的描述:

[HttpPost] 
public ActionResult GetElements(string IDCampana) 
{ 
    Planilla query = db.Planillas.First(); 
    return Json(new 
    { 
     Id = query.IDPlanilla, 
     Description = query.Description 
    }); 
} 

請注意,在這種情況下,匿名對象作爲視圖模型。但如果你真的想要做正確的事情,你會寫你的視圖模型:

public class PlanillaViewModel 
{ 
    public int Id { get; set; } 
    public string Description { get; set; } 
} 

然後:

[HttpPost] 
public ActionResult GetElements(string IDCampana) 
{ 
    Planilla query = db.Planillas.First(); 
    return Json(new PlanillaViewModel 
    { 
     Id = query.IDPlanilla, 
     Description = query.Description 
    }); 
} 

通過Ayende寫了nice series of blog posts這個方式。

+0

我在這裏有個問題:爲什麼我們在VM中添加了2個與我們在領域模型中已經定義的屬性相同的屬性。 –

+1

@ klm9971,我們這樣做是因爲這就是這個特定的視圖(JSON對象)所需要的。另一種觀點可能需要其他屬性。所以我們會爲它定義另一個視圖模型。您應該始終爲每個視圖定義特定的視圖模型。將該視圖看作您商業實體的投影。所以視圖模型只是域模型的投影。 –

+0

明白了,謝謝Darin。 –

1

System.Data.Entity.DynamicProxies.*是Entity Framework的代理名稱空​​間。您的DbContext創建您的實體,以支持延遲加載和更改跟蹤。這不是你的問題。問題可能在於循環關聯。

+0

我同意@Darin Dimitrov,使用視圖模型。 – jrummell