' System.Reflection.TargetInvocationException'发生在EntityFramework.SqlServer.dll中

时间:2017-02-02 13:54:11

标签: c# .net sql-server entity-framework visual-studio

我通过CascadingDropDownListFor调用此方法,并且我得到了例外:

  

类型' System.Reflection.TargetInvocationException'的异常发生在EntityFramework.SqlServer.dll中但未在用户代码中处理

public JsonResult GetRaca(string especieId)
{
    int esp = Convert.ToInt32(especieId);
    var rac = db.Raca.Where(c => c.EspecieId == esp).ToList();
    var racas = new List<SelectListItem>();
    foreach (var ra in rac)
    {
        var racaConteudo = db.RacaConteudo
            .Where(c => c.RacaId == ra.RacaId)
            .Where(c => c.IdiomaId == 1)
            .First(); // <= The exception occurred here

        racas.Add(new SelectListItem 
        {
            Text = racaConteudo.RacaId.ToString(), 
            Value = racaConteudo.NomePopular 
        });
    }

    return Json(racas, JsonRequestBehavior.AllowGet);
}

实体:

[Table("RacasConteudo")]
    public class RacaConteudo
    {
        public RacaConteudo(long RacaId, string NomeCientifico, string NomePopular, long IdiomaId)
        {
            this.RacaId = RacaId;
            this.NomeCientifico = NomeCientifico;
            this.NomePopular = NomePopular;
            this.IdiomaId = IdiomaId;
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long RacaConteudoId { get; set; }

        [ForeignKey("RacaId")]
        public virtual Raca Raca { get; set; }
        public long RacaId { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Nome Cientifico")]
        public string NomeCientifico { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Nome Popular")]
        public string NomePopular { get; set; }

        [ForeignKey("IdiomaId")]
        [Display(Name = "Idioma")]
        public virtual Idioma Idioma { get; set; }
        public long IdiomaId { get; set; }
    }

1 个答案:

答案 0 :(得分:-1)

删除参数化构造函数 public RacaConteudo(long RacaId, ..., long IdiomaId),并使类 部分

[Table("RacasConteudo")]
public partial class RacaConteudo
        ^^^^^
{
   /* public RacaConteudo(...)  {} */

   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public long RacaConteudoId { get; set; }
   ....
}

根据您更新的问题, Raca RacaConteudo 有关系。

如果是这样,您甚至可以在 单个查询 中检索所需的结果,这比为每个Raca查询多个RacaConteudos快得多

public JsonResult GetRaca(string especieId)
{
    int esp = Convert.ToInt32(especieId);

    var result = (from c in db.RacaConteudo
        where c.Raca.EspecieId == esp && c.IdiomaId == 1
        select new {Text = c.NomePopular, Value = c.RacaId.ToString()}).ToList();    

    return Json(result, JsonRequestBehavior.AllowGet);
}