我只是通过遍历类型列表(i.e. Items)
的集合将学生添加到数据库中。此处未对项目进行强类型输入。我从其他地方得到这个。所以我需要从它构造Student对象,然后再将其写入SQL。它具有学生信息。
只要所有字段验证正常,它对我来说就很好。
但是,如果列表中的第一项有验证错误(i.e. Age required field in Student model)
,我会得到很好的错误。但是对于第二个项目,我具有有效的Age值,但仍收到前一个项目的验证错误。
try
{
foreach (var item in Items)
{
Student student = new Student
{
StudentId = item.Id,
Age = item.Age,
Description = item.Description
};
_context.Student.Add(student);
_context.SaveChanges();
}
}
catch (MyCustomValidationException ex)
{
//// catch it and log it
}
它仍然与上下文相关的第一项是否相关?
我该如何摆脱呢?我所有想要通过遍历通过验证的列表将项目保存在DB中的方法。
物品
public class Items
{
public string Id {get;set;}
public string Age {get; set;}
public string Description {get;set;}
}
这就是它的填充方式
items.Add(
new Items
{
new Items {Id = 1, Age = null, Description = "ABC"},
new Items {Id = 1, Age = 12, Description = "ABC"}
}
)
最佳答案
问题是您在Age
中有一个必填字段Student
,但是您为其提供了一个null
值,并且该值无法插入数据库中。
您应该验证要插入数据库的数据。
foreach (var item in Items)
{
Student student = new Student
{
StudentId = item.Id,
Age = item.Age,
Description = item.Description
};
if (student.IsValid())
{
_context.Student.Add(student);
} // else do something with invalid data! maybe warn user or log it ...
}
_context.SaveChanges();
将
IsValid
添加到Student
类public bool IsValid()
{
if (string.IsNullOrWhiteSpace(this.Age))
{
return false;
}
return true;
}
怎么了??
通过调用
Student
将无效的_context.Student.Add(student);
添加到上下文中。每次调用_context.SaveChanges();
时,它都会尝试将添加的Student
插入数据库。您将收到错误,直到您删除无效的Student
。调用SaveChanges
并不是一个好主意,因为每次调用它都会打入数据库,这会增加额外的开销。但是,如果要通过调用SaveChanges()
逐一检查有效性并获取异常,则可以尝试此操作。foreach (var item in Items)
{
Student student = new Student
{
StudentId = item.Id,
Age = item.Age,
Description = item.Description
};
_context.Student.Add(student);
try
{
_context.SaveChanges();
}
catch (MyCustomValidationException ex)
{
_context.Student.Remove(student);
}
}