【发布时间】:2017-03-14 22:16:40
【问题描述】:
我刚刚在我的完整 .net 4.5.2 项目中开始使用 EF Core,并且正在尝试进行集成测试以验证我可以插入一个新学生。
问题是,我希望能够从抛出的异常中获得更好的信息,说明为什么它没有插入到数据库中。
这是我的集成测试代码:
[Fact]
public void save_the_new_student_to_the_database()
{
var fixture = new Fixture();
var optionsBuilder = new DbContextOptionsBuilder<TestDbContext>();
//optionsBuilder.UseInMemoryDatabase();
optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = afmil_Test_next; Trusted_Connection = True; "
);
using (var context = new TestDbContext(optionsBuilder.Options))
{
var command = fixture.Create<PostRegisterStudentCommand>();
var handler = new PostRegisterStudentCommandHandler(context);
try
{
handler.Handle(command);
}
catch (DbUpdateException e)
{
var sb = new StringBuilder();
sb.AppendLine($"DbUpdateException error details - {e?.InnerException?.InnerException?.Message}");
foreach (var eve in e.Entries)
{
sb.AppendLine($"Entity of type {eve.Entity.GetType().Name} in state {eve.State} could not be updated");
}
sb.ShouldBeNull();
}
var dbStudent = context.Students.FirstOrDefault();
dbStudent.ShouldNotBeNull();
dbStudent.User.FirstName.ShouldBe(command.FirstName);
}
}
我从 EF 6 stackoverflow answer 获得了异常捕获部分。
我已经搜索了我能想到的所有内容,以找到在 EF Core 中提取实体验证问题(来自 EF6 的 DbEntityValidationException)的示例,但找不到任何似乎有效的内容。
根据this EF Core github issue 的建议,我尝试进行一些注释验证,例如this。但这并没有发现 db 对我的学生对象存在的问题。
【问题讨论】:
-
我发现了这个 github 问题,但在保存到数据库之前仍然没有发现我的实体的问题。 github.com/aspnet/EntityFramework/issues/4434
标签: c# integration-testing entity-framework-core