我正在使用 Entity Framework 5.0(用于 .NET 4)并使用TimestampAttribute进行乐观并发检查。但是,我看到了奇怪/意外的行为,其中父实体的版本/时间戳被更新,因为它们的子实体被更新。
这最好通过示例代码来解释。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
namespace ConsoleApplication1
{
public abstract class Entity
{
public int Id { get; set; }
public string Name { get; set; }
/*[ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Column(TypeName = "rowversion")]*/
[Timestamp]
public byte[] Version { get; set; }
}
public class Parent : Entity
{
public virtual List<Child> Children { get; set; }
}
public class Child : Entity
{
public virtual Parent Parent { get; set; }
// Uncommenting property below causes the parent version to be unexpectedly updated when its child is updated.
// This occurs regardless of whether the Version property is decorated with [Timestamp] or [ConcurrencyCheck].
//public int? ParentId { get; set; }
}
public class TestDbContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TestDbContext>());
var child = new Child {Name = "Child"};
var parent = new Parent {Name = "Parent", Children = new List<Child> {child}};
using (var context = new TestDbContext())
{
context.Parents.Add(parent);
context.SaveChanges();
var originalParentVersion = parent.Version.ToArray();
child.Name = "New Child Name";
context.SaveChanges();
if (!originalParentVersion.SequenceEqual(parent.Version))
throw new Exception("Not expected");
}
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
如果我按原样运行这个简单的控制台应用程序,则不会引发“非预期”异常。但是,如果我取消注释 ID 外键属性 (ParentID),则会引发异常。
谁能解释这种奇怪的行为?这是一个错误吗?