如何在C#中的foreach循环中实例化并添加到类中

时间:2013-08-15 14:28:25

标签: c#

我有用于记录错误消息的代码。我创建了两个这样的类来保存消息:

public class HttpStatusErrors
{
    public HttpStatusErrors()
    {
        this.Details = new List<HttpStatusErrorDetails>();
    }
    public string Header { set; get; }
    public IList<HttpStatusErrorDetails> Details { set; get; }
}
public class HttpStatusErrorDetails
{
    public HttpStatusErrorDetails()
    {
        this.Details = new List<string>();
    }
    public string Header { set; get; }
    public IList<string> Details { set; get; }
}

我认为这是一个很好的方法,但我不是百分百肯定,并欢迎任何建议。

我想要做的是在第一个类中存储Header,在我的示例中,它将是“验证消息”。然后在Detail对象中,我想存储另一个Header,它显示实体有错误,最后在Details存储验证错误。

我感到困惑的是我应该如何实例化这些类。到目前为止我已经这样做了。我认为这是正确的。但是我如何添加我需要添加的细节:

catch (DbEntityValidationException ex)
{
    var msg = new HttpStatusErrors();
    msg.Header = "Validation Error";

    foreach (var eve in ex.EntityValidationErrors)
    {
        var header = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            var detail = string.Format("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }

    }

}.

2 个答案:

答案 0 :(得分:2)

Details属性中实例化集合。实例化新项目,并将它们循环添加到集合中:

var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
msg.Details = new List<HttpStatusErrorDetails>();

foreach (var eve in ex.EntityValidationErrors)
{
    var detail = new HttpStatusErrorDetails()
    detail.Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
        eve.Entry.Entity.GetType().Name, eve.Entry.State);

    detail.Details = new List<string>();
    foreach (var ve in eve.ValidationErrors)
    {
        detail.Details.Add(String.Format("- Property: \"{0}\", Error: \"{1}\"",
            ve.PropertyName, ve.ErrorMessage));
    }

    msg.Details.Add(detail);
}

顺便说一句,你可以使用LINQ:

var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
msg.Details =
    ex.EntityValidationErrors
      .Select(eve => new HttpStatusErrorDetails {
                Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)
                Details = eve.ValidationErrors
                         .Select(ve => String.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage))
                         .ToList()
       }).ToList();

我也喜欢扩展方法语法:

 public static HttpStatusErrors ToHttpStatusErrors(
      this DbEntityValidationException ex)
 {
      return new HttpStatusErrors {
          Header = "Validation Error",
          Details = ex.EntityValidationErrors
                      .Select(eve => eve.ToHttpStatusErrorDetails())
                      .ToList()
      };
 }

 public static HttpStatusErrorDetails ToHttpStatusErrorDetails(
      this DbEntityValidationResult eve)
 {
      return new HttpStatusErrorDetails {
        Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                               eve.Entry.Entity.GetType().Name, eve.Entry.State),
        Details = eve.ValidationErrors
                     .Select(ve => ve.ToErrorDescription())
                     .ToList()
      };
 }

 public static string ToErrorDescription(
      this DbValidationError ve)
 {
      return String.Format("- Property: \"{0}\", Error: \"{1}\"",
                           ve.PropertyName, ve.ErrorMessage);
 }

此类方法的用法如下:

catch (DbEntityValidationException ex)
{
    var msg = ex.ToHttpStatusErrors();
}

答案 1 :(得分:0)

尝试以下方法:

foreach (var eve in ex.EntityValidationErrors)
{
    //New Details Entity
    var errorDetail = new HttpStatusErrorDetails();

    //Fill in Header
    errorDetail.Header = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
        eve.Entry.Entity.GetType().Name, eve.Entry.State);

    //Fill Add a detail for each validation error
    foreach (var ve in eve.ValidationErrors)
    {
        errorDetail.Details.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"",
            ve.PropertyName, ve.ErrorMessage));
    }

    //Add Detail to header
    msg.Details.Add(errorDetail);
}