实体定义如下
public class BlogPost
{
[MaxLength(150)]
public string Title { get; set; }
}
请问在 EF Core SaveChanges 保存到数据库之间如何验证 Title 是否超过 MaxLength 的限制,以避免下面的错误?
String or binary data would be truncated.
The statement has been terminated.
都忘了之前解决过这个问题(C#中手工进行声明式验证,从此远离if验证),实现代码如下:
static void Main(string[] args)
{
var blogPost = new BlogPost();
blogPost.Title = new string('*', 200);
var validationContext = new ValidationContext(blogPost);
var validationResults = new List<ValidationResult>();
var succcess = Validator.TryValidateObject(blogPost, validationContext, validationResults, true);
if (!succcess)
{
Console.WriteLine(string.Join("\n", validationResults.Select(r => r.ErrorMessage)));
}
}
可以重写 SaveChanges 方法,在 SaveChanges 之前用 ChangeTracker 做一些检查
foreach (var entry in ChangeTracker.Entries<CommunityOwner>()) { if (entry.State == EntityState.Added) { entry.Entity.UpdatedAt = DateTime.UtcNow; // 判断是否满足自动审核通过条件 if (await IsCanAutoApprove(entry.Entity.UpdatedBy)) { entry.Entity.State = MockingJ.Models.EntityState.Reviewed; } } }