我需要在保存时将任何空文本字段更改为空字符串。在我的下面的代码(基于this post)中,Validator.TryValidateObject()
即使实体中有一些空字符串,也会返回true
。然后dbContext.SaveChanges()
抛出Microsoft.EntityFrameworkCore.DbUpdateException
,内部SqlException
说“无法将值NULL插入X列。”
为什么Validator.TryValidateObject()
无法抓住此null
列,我该如何解决?
抓住SqlException
很尴尬,因为很难找出哪个列是null
,更不用说try-catch
的效率低了。
public static void SaveChangesWithEmptyStrings(this DbContext dbContext) {
var entities =
from e in dbContext.ChangeTracker.Entries()
where e.State == EntityState.Added
|| e.State == EntityState.Modified
select e.Entity;
foreach (var entity in entities) {
var validationContext = new ValidationContext(entity);
List<ValidationResult> results = new List<ValidationResult>();
if (Validator.TryValidateObject(entity, validationContext, results))
continue;
foreach (ValidationResult result in results)
if (result.ErrorMessage.Contains("Cannot insert the value NULL"))
foreach (string name in result.MemberNames)
// Code to set the column to an empty string
}
dbContext.SaveChanges();
}