Map a column to be IDENTITY in db

戏子无情 提交于 2020-01-05 16:32:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!