问题
Although I have marked my ID column with .Identity()
, the generated database schema doesn't have IDENTITY
set to true, which gives me problems when I'm adding records. If I manually edit the database schema (in SQL Management Studio) to have the Id
column marked IDENTITY
, everything works as I want it - I just can't make EF do that by itself.
This is my complete mapping:
public class EntryConfiguration : EntityConfiguration<Entry>
{
public EntryConfiguration()
{
Property(e => e.Id).IsIdentity();
Property(e => e.Amount);
Property(e => e.Description).IsRequired();
Property(e => e.TransactionDate);
Relationship(e => (ICollection<Tag>)e.Tags).FromProperty(t => t.Entries);
}
}
As I'm using EF to build and re-build the database for integration testing, I really need this to be done automatically...
EDIT: Hm... In a comment I was requested to give enough code to execute this, so I cut-and-pasted my code into a console app (so you wouldn't need all my classes...) and suddenly it just worked. I guess I was forgetting some method call somewhere, although I haven't been able to figure out where.
I'll post the working solution code in an answer to this post, in case someone else comes looking for it.
回答1:
Running this code solves the problem. I guess I must have forgot a step somewhere, so if you have the same problem, make sure you do all these things:
var connection = GetUnOpenedSqlConnection(); // Any connection that inherits
// from DbConnection is fine.
var builder = new ContextBuilder<ObjectContext>(); // I actually had my own class
// that inherits from
// ObjectContext, but that was
// not the issue (I checked).
builder.Configurations.Add(EntryConfiguration); // EntryConfiguration is the
// class in the question
var context = builder.Create(connection);
if (context.DatabaseExists())
{ context.DeleteDatabase(); }
context.CreateDatabase();
来源:https://stackoverflow.com/questions/2603148/map-a-column-to-be-identity-in-db