简体   繁体   English

实体框架更新记录问题(无法为属性调用成员'IsModified')

[英]Entity Framework Update record issue (Member 'IsModified' cannot be called for property)

I'm having some problems updating a record using Entity Framework 6. 我在使用Entity Framework 6更新记录时遇到了一些问题。

    public bool UpdateOrder(Order order)
    {
        Db.Orders.Attach(order);
        var entry = Db.Entry(order);
        entry.Property(x => x.OrderStatusId).IsModified = true; //Exception thrown
        try
        {
            Db.SaveChanges();
        }
        catch (Exception e)
        {
            logger.Fatal(e);
        }
        return true;
    }

This is the exception message: 这是异常消息:

Member 'IsModified' cannot be called for property 'OrderStatusId' because the entity of type 'Order' does not exist in the context. 无法为属性“OrderStatusId”调用成员“IsModified”,因为上下文中不存在“Order”类型的实体。 To add an entity to the context call the Add or Attach method of DbSet. 要向上下文添加实体,请调用DbSet的Add或Attach方法。

I tried changing entry.Property(x => x.OrderStatusId).IsModified = true; 我尝试更改entry.Property(x => x.OrderStatusId).IsModified = true; to entry.State = EntityState.Modified; to entry.State = EntityState.Modified; But my record does not then get updated. 但是我的记录没有得到更新。 Any ideas how to help? 任何想法如何帮助?

Apologies if this is obvious but I'm new to using EF and I cannot find how to fix this. 抱歉,如果这是显而易见的,但我是新手使用EF,我找不到如何解决这个问题。

I fixed it by: 我修复了:

public bool UpdateOrder(Order order)
    {
using(var db = DB){
            db.Orders.Attach(order);
            var entry = db.Entry(order);
            entry.Property(x => x.OrderStatusId).IsModified = true; //Exception thrown
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                logger.Fatal(e);
            }
            return true;
}
        }

Probably the reason of the exception is the default value in the Id field (primary key) of the "order" object. 可能异常的原因是“order”对象的Id字段(主键)中的默认值。 For int it is 0. In this case "order" is considered as a new object and should be added with "add" method. 对于int,它为0.在这种情况下,“order”被视为一个新对象,应该使用“add”方法添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM