首页 > 解决方案 > 数据库并发异常

问题描述

我们正在为我们的研究项目开发数据库,​​在向表中添加数据时出现意外错误。

using (var ctx = new BazyDanychContext())
{
    Osoba tmpTask = new Osoba { Imie = ImieLbl.Text, Nazwisko = NazwiskoLbl.Text, Telefon = TelefonLbl.Text, Adres = AdresLbl.Text, Mail = MailLbl.Text, IloscTransakcji = Int32.Parse(IloscLbl.Text), Typ = TypList.Text };
    ctx.Osoba.Add(tmpTask);
    ctx.SaveChanges();
}

我们也试过:

无论我们做什么,ctx.SaveChanges()都给我们

OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0).

我们的课程:

namespace BazyDanych
{ 
    public class BazyDanychContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }
        public BazyDanychContext() : base("ProjektBD")
        {
            Database.SetInitializer(new SQLdb());
        }

        public DbSet<Osoba> Osoba { get; set; }
    }
}

namespace BazyDanych
{
    public class Osoba
    {
        public int ID { get; set; }
        public string Imie { get; set; }
        public string Nazwisko { get; set; }
        public string Telefon { get; set; }
        public string Adres { get; set; }
        public string Mail { get; set; }
        public int IloscTransakcji { get; set; }
        public string Typ { get; set; }

        public override string ToString()
        {
            return "Imie: " + Imie + "\t Nazwisko: " + Nazwisko + "\t ID: " + ID.ToString();
        }
    }
}

数据库表的结构如下:

ID (int, null)
Imie (text, null)
Nazwisko (text, null)
Telefon (text, null)
Adres (text, null)
Mail (text, null)
IloscTransakcji (int, null)
Typ (text, null)

标签: c#entity-frameworkconcurrency

解决方案


看起来在您的 C# Entity Framework 代码中,您没有包含 ID 值,这意味着您将其设置为自动增量作为 IDENTITY 值。但是,在您的INSERT声明中,您为其包含了一个值,如果您将其设置为 IDENTIY 值,则该值将不起作用。要解决您的问题,您可以执行以下两项操作之一:

  1. 将您的列更改ID为自动增量。 这将允许您保持 C# 代码原样,并且它应该按预期工作而无需提供值。如果您不想直接对插入的值负责,请执行此操作。

  2. 在列的 EF 代码中包含一个值ID

    using (var ctx = new BazyDanychContext())
    {
        Osoba tmpTask = new Osoba { ID = IDLbl.Text, Imie = ImieLbl.Text, Nazwisko = NazwiskoLbl.Text, Telefon = TelefonLbl.Text, Adres = AdresLbl.Text, Mail = MailLbl.Text, IloscTransakcji = Int32.Parse(IloscLbl.Text), Typ = TypList.Text };
        ctx.Osoba.Add(tmpTask);
        ctx.SaveChanges();
    }
    

推荐阅读