2011-10-19 66 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