我是EF(v6.1)的新手。试图使用Code-First方法。
我想要在SQL服务器端生成Id列(newsequentialid()
),但可以覆盖这些值。 我的代码:EF6.1 newsequentialid能够手动设置值
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
导致完美SQL:
[Id] [uniqueidentifier] NOT NULL DEFAULT (newsequentialid())
但是EF简单地忽略我会设置为Id
财产和传递null SQL任意值。本质上以下测试不起作用:
MyContext context = new MyContext();
MyClass item = new MyClass();
Guid id = Guid.NewGuid();
item.Id = id;
context.MyTable.Add(item);
context.MyTable.Create();
context.SaveChanges();
Assert.AreEqual(item.Id, id);
我该如何做我的测试工作?
只需创建第二个'DbContext'子类,该子类将“MyClass”(但在别名下)映射到同一个表,而不需要'DatabaseGeneratedOption.Identity'。使用这个类来处理特殊情况。 –