我正在使用最新的 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";
}
在调用
Add
方法之前,您必须填写列表,尝试更改:
var theOrder = new Order();
dbContext.Orders.Add(theOrder);
theOrder.OrderLines.Add(new OrderLine());
dbContext.SaveChanges();
到
var theOrder = new Order();
theOrder.OrderLines.Add(new OrderLine());
dbContext.Orders.Add(theOrder);
dbContext.SaveChanges();