c# - 数据库并发异常
问题描述
我们正在为我们的研究项目开发数据库,在向表中添加数据时出现意外错误。
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();
}
我们也试过:
使用 ExecuteSqlCommand 添加新记录,效果很好
ctx.Database.ExecuteSqlCommand("INSERT INTO dbo.Osoba VALUES('0','jan','nowak', '222222', 'adres', 'mail', '2', 'osoba')");
使用
ctx.Entry(tmpTask).State = System.Data.Entity.EntityState.Added;
(也.Modified
)手动键入值(如在 ExecuteSqlCommand 行中)
无论我们做什么,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 Framework 代码中,您没有包含 ID 值,这意味着您将其设置为自动增量作为 IDENTITY 值。但是,在您的INSERT
声明中,您为其包含了一个值,如果您将其设置为 IDENTIY 值,则该值将不起作用。要解决您的问题,您可以执行以下两项操作之一:
将您的列更改
ID
为自动增量。 这将允许您保持 C# 代码原样,并且它应该按预期工作而无需提供值。如果您不想直接对插入的值负责,请执行此操作。在列的 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(); }
推荐阅读
- css - 如何将图像增加到全屏?
- windows - SSH from rsync on Windows
- python - 获取无效或意外的令牌错误
- json - WoT 抽认卡连接到 MyJSON
- flutter - 在 Flutter 中缓存离线请求?
- javascript - 如何在 Vuetify 中制作条纹 v-data-table?
- c - Modern way to read gamepad input with C on Linux
- amazon-dynamodb - Reassigning the primary search key to another key within my item, is this possible? (DynamoDB)
- ckeditor - CKEditor 禁用链接双击对话框出现
- python - 查找用户输入的一组值的最大值而不将值存储在列表中