问题
I'm new to EF(v6.1). Trying to use Code-First approach.
I would like to have Id column to be generated on SQL server side (newsequentialid()), however with ability to override those values.
My code:
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
Which results in perfect SQL:
[Id] [uniqueidentifier] NOT NULL DEFAULT (newsequentialid())
However EF simply ignores any value I would set to Id property and pass null to SQL. Essentially follwing test wouldn't work:
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);
What should I do to make my test work?
回答1:
If you want to set manually your Guid Id property then remove DatabaseGenerated attribute:
[Key]
public Guid Id { get; set; }
If you configure your PK property as Identity, the value will be generated in your DB.Also, you don't need to mark this property as Required, PK properties are required by default.
来源:https://stackoverflow.com/questions/40598817/ef6-1-newsequentialid-with-ability-to-set-value-manually