为什么 DbContext.Attach 将实体状态设置为 EntityState.Modified?

Why does the DbContext.Attach set an entity state to EntityState.Modified?

为什么 DbContext.Attach 在以下示例中将实体状态设置为 EntityState.Modified

var db = new TestContext();
var book = new Book { 
    BookId = 1, 
    Author = new Author {
        FirstName = "Charles", 
        LastName = "Dickens" 
    } 
};
db.Attach(book); // Book Modified, Author Added - no "store generated key"

例子取自here.

根据Attach方法描述方法:

Tells EF that the entity already exists in the database, and sets the state of the entity to Unchanged.

因此,在上面的示例中,我希望 BookUnchanged,而不是 Modified。我在这里遗漏了什么吗?

更新

尝试代码后,我发现它根本行不通。那是因为我们只能对一组对象执行 Attach 操作。因此,db.Attach(book); 应更改为 db.Books.Attach(book);。但我仍然不明白是什么让 Attach 方法将实体的状态设置为 Modified,而不是 Unchanged.

我没有看到您描述的行为。我将此代码添加到 your fiddle:

using (var context = new EntityContext())
{
    var customer = new Customer() {CustomerID = 1};
    context.Customers.Attach(customer);
    var entity = context.Entry(customer);

    Console.WriteLine(entity.State);
}

输出为:

Unchanged

就像the documentation说的那样。

也许该评论 (// Book Modified, Author Added - no "store generated key") 是一个错误,或者描述了他们打算将作者添加到其中。在这种情况下,您必须在调用 SaveChanges 之前将记录设置为 Modified,或者在调用 Attach 之后 修改您想要修改的内容 ],像这样:

using (var context = new EntityContext())
{
    var customer = new Customer() {CustomerID = 1};
    context.Customers.Attach(customer);

    //change something
    customer.Description = "something";

    var entity = context.Entry(customer);
    Console.WriteLine(entity.State);
}

现在会显示 Modified