当 IDENTITY_INSERT 在 Entity Framework 中设置为 OFF 时无法插入显式值

Cannot insert explicit value when IDENTITY_INSERT is set to OFF in Entity Framework

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

Cannot insert explicit value for identity column in table "Terms" when IDENTITY_INSERT is set to OFF

异常在 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; }
    }
}

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

//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++;