简体   繁体   English

用户代码未处理实体异常

[英]entity exception was unhandled by user code

I am getting an error called "entity exception was unhandled by user code" in the foreach loop. 我在foreach循环中收到一个名为“用户代码未处理实体异常”的错误。 Why is this happening? 为什么会这样呢? What am i doing wrong? 我究竟做错了什么?

    public IList<ProductDTO> GetProducts()
    {
        IList<ProductDTO> listofproducts = new List<ProductDTO>();
        using (var db = new NORTHWNDEntities())
        {
            var query = from p in db.Products
                        select new
                                   {
                                       Name = p.ProductName,
                                   };

The error happens right her in the foreach. 错误正好发生在她的foreach中。

                *foreach (var product in query)*
                {
                    listofproducts.Add(new ProductDTO { Name = product.Name });
                }
            }
        return listofproducts;

    }

If you want to find the exact problem where is the problem please write code in try catch statement in this way 如果您想找到确切的问题所在,请以这种方式在try catch语句中编写代码

try
{
  //write code

} 
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                var outputLines = new List<string>();
                foreach (var eve in ex.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format(
                            "- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"c:\temp\errors.txt", outputLines);
            }

First of all check if you can access data source. 首先检查是否可以访问数据源。 If it is fine then you need to check your query structure. 如果可以,则需要检查查询结构。 You are iterating through the query but not through query results. 您正在遍历查询,而不是遍历查询结果。 Use ToList method to convert the query to List to iterate through it. 使用ToList方法将查询转换为List以便对其进行迭代。 You need to to use Enumerable.ToList method to convert the query results to list. 您需要使用Enumerable.ToList方法将查询结果转换为列表。

var query = (from p in db.Products
              select new
              {
                    Name = p.ProductName,
              }).ToList();

foreach (var product in query)*
{
      listofproducts.Add(new ProductDTO { Name = product.Name });
}

You can directly create object of ProductDTO using projection. 您可以使用投影直接创建ProductDTO对象。

IList<ProductDTO> listOfProcuts = (from p in db.Products
                                   select new ProductDTO 
                                   {
                                       Name = p.ProductName,
                                   }).ToList();

return listOfProcuts ;

Adil's answer is correct and would solve your problem, but you might consider returning IEnumerable<ProductDTO> instead of IList<DTO> . Adil的答案是正确的,可以解决您的问题,但是您可以考虑返回IEnumerable<ProductDTO>而不是IList<DTO>

Following the principle of information hiding, if the other parts of the program that call GetProducts() do not need list semantics then they shouldn't see the IList<T> semantics 遵循信息隐藏的原理,如果程序的其他调用GetProducts()的部分不需要列表语义,则它们不应看到IList<T>语义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM