提问人:walie 提问时间:10/9/2023 最后编辑:Svyatoslav Danylivwalie 更新时间:10/9/2023 访问量:64
将项添加到现有集合 - 数据库操作预计会影响 1 行,但实际上影响了 0 行
Adding items to existing collection - The database operation was expected to affect 1 row(s), but actually affected 0 row(s)
问:
我正在使用最新的 ef core 7.0.11。运行 CanInsertOrderline2 测试时,出现以下错误。
数据库操作预计会影响 1 行,但实际上影响了 0 行;自加载实体以来,数据可能已被修改或删除
但另一个测试 (CanInsertOrderline1) 按预期工作。
如果我将订单线添加到上下文中,它就会正常工作。
secondContext.OrderLines.Add(secondOrder.OrderLines[0]);
任何想法都非常感谢。
[Test]
public void CanInsertOrderline2()
{
//This Throws an exception
var dbContext = new OrderContext();
ResetDatabase(dbContext);
var theOrder = new Order();
dbContext.Orders.Add(theOrder);
dbContext.SaveChanges();
Assert.That(new OrderContext().Orders.Count(), Is.EqualTo(1));
var secondContext = new OrderContext();
var secondOrder = secondContext.Orders
.Include(i => i.OrderLines)
.First();
secondOrder.OrderLines.Add(new OrderLine());
secondContext.SaveChanges();
var otherContext = new OrderContext();
Assert.That(otherContext.Orders.Count(), Is.EqualTo(1), "Order");
Assert.That(otherContext.OrderLines.Count(), Is.EqualTo(1), "OrderLines");
}
[Test]
public void CanInsertOrderline1()
{
var dbContext = new OrderContext();
ResetDatabase(dbContext);
var theOrder = new Order();
dbContext.Orders.Add(theOrder);
theOrder.OrderLines.Add(new OrderLine());
dbContext.SaveChanges();
var otherContext = new OrderContext();
Assert.That(otherContext.Orders.Count(), Is.EqualTo(1));
Assert.That(otherContext.OrderLines.Count(), Is.EqualTo(1));
}
public class Order
{
public Order()
{ }
public Guid Id { get; set; } = Guid.NewGuid();
public List<OrderLine> OrderLines { get; set; } = new();
}
public class OrderLine
{
public Guid Id { get; set; } = Guid.NewGuid();
public string ProductText { get; set; } = "ProductText";
}
答: 暂无答案
评论
unit tests
EF Core