带迁移的CodeFirst种子中的错误:不支持使用"标识"模式修改列.专栏:'CreatedAt'.

Ale*_*ung 5 c# entity-framework azure azure-mobile-services

我已在Azure Mobile Services项目上激活了迁移.我在迁移的Configuration.cs类中填充了新的种子函数.如果表是空的,则种子功能没有任何问题.当我的AddorUpdate尝试更新第一个对象时,我在内部异常中收到错误:"不支持修改具有'Identity'模式的列.列:'CreatedAt'.表:'CodeFirstDatabaseSchema.Category'."

我的部分代码如下:

context.categories.AddOrUpdate(
            new Category { Id="1", Code="GEN", Text="General"},
            new Category { Id="2", Code="POL", Text="Politics"},
            new Category { Id="3", Code="FAS", Text="Fashion"},
            new Category { Id="4", Code="PEO", Text="People"},
            new Category { Id="5", Code="TEC", Text="Technology"},
            new Category { Id="6", Code="SPO", Text="Sport"},
            new Category { Id="7", Code="LIV", Text="Living"}
        );
Run Code Online (Sandbox Code Playgroud)

Fer*_*hen 6

这是我对 Nikatlas 解决方案的通用实现。

答案的简短版本:您不能使用空值修改 CreatedAt,因此您可以改用此函数:

    private void AddOrUpdatePreservingCreatedAt<T> (DbSet<T> set, T item) where T : EntityData
    {        
        var existing = set.Where(i => i.Id == item.Id).FirstOrDefault();
        if (existing != null)
        {
            item.CreatedAt = existing.CreatedAt;             
        }
        set.AddOrUpdate(i => i.Id, item);
    }
Run Code Online (Sandbox Code Playgroud)

像这样称呼

AddOrUpdatePreservingCreatedAt(context.YourItems, itemToBeUpdatedOrAdded);
Run Code Online (Sandbox Code Playgroud)


ast*_*kov 0

这个问题、它的答案和评论可能对你有一点帮助,但不多。

您可以使用问题提供的解决方案在标识列上插入。但您无法更新标识列的值。对身份列进行更新的唯一方法是将其标记为不是身份。可能通过添加手动迁移。

这个问题及其答案也可能有帮助。

另请阅读此处有关更新身份列的一般 MSSQL Server 限制