实体框架代码优先中的奇怪实体更新

Kyr*_*o M 6 c# entity-framework ef-code-first asp.net-mvc-3

我在保存到数据库之前更新实体并解决了这个问题.

我在ASP.NET MVC 3 Web应用程序中使用Entity Framework 4.1 Code-First.这是模型:

public class Order
{
    public int OrderId { get; set; }
    public int CarId { get; set; }
    public DateTime BeginRentDate { get; set; }
    public DateTime EndRentDate { get; set; }
    public decimal RentPrice { get; set; }
    public virtual Car Car { get; set; }
}

public class Car
{
    public int CarId { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string NumberPlate { get; set; }
    public decimal RentPrice { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

每辆车都有RentPrice.创建一个时,应将此价格复制到Order的RentPrice.汽车正由用户选择,因此最初Order.RentPrice为0.

在这里我要复制价格值:

[HttpPost]
public ActionResult Create(Order order)
{
    order.RentPrice = _context.Cars.Find(order.CarId).RentPrice;

    if (ModelState.IsValid)
    {
        _context.Orders.Add(order);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(order);
}
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为SaveChanges该实体有错误验证错误.好.我发现需要先调用UpdateModel(order);然后更改值.

所以我拥有.工作代码:

_context.Orders.Add(order);
UpdateModel(order);
order.RentPrice = 777;
_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

工作的代码:

_context.Orders.Add(order);
UpdateModel(order);
order.RentPrice = _context.Cars.Find(order.CarId).RentPrice;
_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

工作代码(!):

_context.Orders.Add(order);
UpdateModel(order);
var t = (double)_context.Cars.Find(order.CarId).RentPrice;
order.RentPrice = (decimal)t;
_context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下,这里发生了什么?特别是最后一段代码中第3行和第4行的魔术.

更新

我得到DbEntityValidationException:"一个或多个实体的验证失败.有关详细信息,请参阅'EntityValidationErrors'属性." 从内部异常:"OriginalValues不能用于处于已添加状态的实体."

Joh*_*ohn 18

当你拿到时

"一个或多个实体的验证失败.有关详细信息,请参阅'EntityValidationErrors'属性." 从内部异常:"OriginalValues不能用于处于已添加状态的实体."

这意味着存在诸如空白或其他约束的NOT NULL collumns之类的错误,通过调试等检查实体验证错误

try{
...
catch ( DbEntityValidationException ex )
   {
foreach ( var validationErrors in ex.EntityValidationErrors )
    {
     foreach ( var validationError in validationErrors.ValidationErrors )
     {
      System.Diagnostics.Trace.TraceInformation( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage );
     }
    }
}
Run Code Online (Sandbox Code Playgroud)


zs2*_*020 0

您是否在任何地方声明了主键?您应该使用 FluentAPI 或如下属性来执行此操作:

public class Order
{
    [Key]
    public int OrderId { get; set; }
    public int CarId { get; set; }
    public DateTime BeginRentDate { get; set; }
    public DateTime EndRentDate { get; set; }
    public decimal RentPrice { get; set; }
    public virtual Car Car { get; set; }
}

public class Car
{
    [Key]
    public int CarId { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string NumberPlate { get; set; }
    public decimal RentPrice { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

或者在您的上下文中,您可以使用 Fluent API 来声明密钥,如下所示

builder.Entity<Car>().HasKey(x=>x.CarId);
builder.Entity<Order>().HasKey(x=>x.OrderId);
Run Code Online (Sandbox Code Playgroud)