【问题标题】:Cannot insert explicit value when IDENTITY_INSERT is set to OFF in Entity Framework在实体框架中将 IDENTITY_INSERT 设置为 OFF 时无法插入显式值
【发布时间】:2020-06-06 04:25:07
【问题描述】:

我正在尝试将数据添加到我的数据库中,但我不断收到此错误:

当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Terms”中插入标识列的显式值

SaveChanges() 上引发异常。我已经尝试过使用上面的[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public int TermId { get; set; }

以及我在这里找到的所有其他想法,但没有任何效果。我不知道该尝试什么了。

这是OnPost 方法的一部分:

try
{
    int? termId;

    while ((termId = ReadTermId(ligne, worksheet)) != null)
    {
        var term = worksheet.Cell(ligne, 2).Value.ToString();
        var definition = worksheet.Cell(ligne, 3).Value.ToString();
        var listExamplesEntities = new List<Example>();

        foreach (var cell in worksheet.Cell(ligne, 4).ToString().Split("\n"))
        {
            listExamplesEntities.Add(new Example {TermId = termId.Value, LocalizationId = language, Text = cell});
        }

        var notes = worksheet.Cell(ligne, 6).Value.ToString();
        var occurence = worksheet.Cell(ligne, 7).Value.ToString();
        var roots = worksheet.Cell(ligne, 8).Value.ToString();
        var rootsEntities = new List<Root>();

        if (!string.IsNullOrWhiteSpace(roots))
        {
            var rawRoots = roots.Trim().Split("\n");

            for (int i = 0; i < rawRoots.Length; i += 2)
            {
                var description = "";

                if (i < rawRoots.Length - 1) 
                    description = rawRoots[i + 1];

                rootsEntities.Add(new Root { TermId = termId.Value, LocalizationId = language,
                                Definition = description, Word = rawRoots[0]});

                if (!string.IsNullOrWhiteSpace(description)) 
                     i++;
            }
        }

        // Create and add term
        var termEntity = new Term
                    { 
                        TermId = termId.Value
                    };

        if (db.Terms.Find(termId.Value) == null)
        {
            db.Terms.Add(termEntity);
        }
        else
        {
            db.Terms.Update(termEntity);
        }

        // Create and add termLocalization
        TermLocalization termLocalizationEntity = new TermLocalization
                    {
                        TermId = termId.Value,
                        Term = db.Terms.Find(language),
                        LocalizationId = language,
                        Localization = db.Localizations.Find(language),
                        Roots = rootsEntities,
                        Examples = listExamplesEntities,
                        Word = term,
                        Definition = definition,
                        Note = notes,
                        FirstOccurence = occurence,
                        LastUpdateDate = DateTime.Today
                    };

        if(db.TermLocalizations.SingleOrDefaultAsync(x => x.TermId == termId && x.LocalizationId == language).Result == null)
        {
            db.TermLocalizations.Add(termLocalizationEntity);
        }
        else
        {
            db.TermLocalizations.Update(termLocalizationEntity);
        }

        db.SaveChanges();

        ligne++;
    }

    Confirmation = "Le fichier a été téléchargé avec succès";
}
catch (Exception ex)
{
    Confirmation = "Fichier invalide à la ligne " + ligne;
}

这是我的Term 实体:

namespace ENAP.Domain.Entities
{
    public class Term
    {
        public int TermId { get; set; }
    }
}

【问题讨论】:

  • 看起来错误来自带有标识列的 SQL Server 表。身份列将自动为您生成一个 ID。如果您不需要该功能,您可以更新表以禁用 Identity 列。如果这对您更有效,可以add explicit values to an Identity
  • 您需要将[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 放在表示数据库表中标识列的(不是)上
  • 当您将属性更改为 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 时,您需要进行新的迁移。

标签: c# asp.net-mvc entity-framework-core ssms


【解决方案1】:

我找到了解决问题的方法。它可能不是最干净的代码,但它工作得很好。

//Create and add term
var transaction = await db.Database.BeginTransactionAsync();

var termEntity = new Term
{
     TermId = termId.Value
};
if (db.Terms.Find(termId.Value) == null)
{
    db.Terms.Add(termEntity);
}
else
{
    db.Terms.Update(termEntity);
}
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Terms ON;");
await db.SaveChangesAsync();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Terms OFF");

//Create and add termLocalization
TermLocalization termLocalizationEntity = new TermLocalization
{
    TermId = termId.Value,
    LocalizationId = language,
    Roots = rootsEntities,
    Examples = listExamplesEntities,
    Word = term,
    Definition = definition,
    Note = notes,
    FirstOccurence = occurence,
    LastUpdateDate = DateTime.Today
};

if (db.TermLocalizations.SingleOrDefaultAsync(x => x.TermId == termId && x.LocalizationId == language).Result == null)
{
    db.TermLocalizations.Add(termLocalizationEntity);
}
else
{
    db.TermLocalizations.Update(termLocalizationEntity);
}
await db.SaveChangesAsync();
await transaction.CommitAsync();

ligne++;

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 2018-06-22
    • 2014-05-24
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多