尽管我已经标记了我的ID列 .Identity(), ,生成的数据库模式没有 IDENTITY 设置为true,当我添加记录时,这给了我问题。如果我手动编辑数据库架构(在SQL Management Studio中) Id 列标记 IDENTITY, ,一切都按照我的需求工作 - 我只是无法让EF本身做到这一点。

这是我的完整映射:

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);
    }
}

当我使用EF来构建和重建数据库进行集成测试时,我确实需要自动完成此操作...

编辑:hm ...在评论中,我被要求提供足够的代码来执行此操作,因此我将代码剪切到游戏机应用程序中(因此您不需要我所有的课程...) 。我想我忘记了某个地方的方法,尽管我无法弄清楚哪里。

如果有人来找它,我将在回答本文的答案中发布工作解决方案代码。

有帮助吗?

解决方案

运行此代码解决了问题。我想我一定已经忘记了某个地方的一步,因此,如果您有同样的问题,请确保您做所有这些事情:

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top