【发布时间】:2020-06-01 23:15:29
【问题描述】:
我正在尝试在数据库中保存多条记录,数据在列表中正确存储,但是当我按下按钮保存到数据库时,它不起作用。
列表中只有一条记录并按下按钮 2 没有任何反应,但列表中有超过 2 条记录并按下按钮 2 程序崩溃并出现以下错误代码:
Microsoft.EntityFrameworkCore.DbUpdateException: '更新条目时出错。有关详细信息,请参阅内部异常。'
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“roll”中插入标识列的显式值
我的错误是什么?
变量:
int p = 0;
string x = "";
decimal xx = 0;
string v = "";
decimal vv = 0;
string f = "";
decimal ff = 0;
decimal pp = 0;
List<int> piece = new List<int>();
List<string> protein = new List<string>();
List<string> vegetable = new List<string>();
List<string> wrapped = new List<string>();
List<decimal> piecePrice = new List<decimal>();
List<decimal> proteinPrice = new List<decimal>();
List<decimal> vegetablePrice = new List<decimal>();
List<decimal> wrappedPrice = new List<decimal>();
按钮点击:
private void button1_Click(object sender, EventArgs e)
{
piece.Add(Convert.ToInt32(comboBox1.SelectedValue.ToString()));
protein.Add(comboBox2.SelectedValue.ToString());
vegetable.Add(comboBox3.SelectedValue.ToString());
wrapped.Add(comboBox4.SelectedValue.ToString());
for (int i = 0; i < piece.Count(); i++)
{
var p = piece[piece.Count - 1];
var h = protein[protein.Count - 1];
var v = vegetable[vegetable.Count - 1];
var f = wrapped[ wrapped.Count - 1];
using (var context = new AppDbContext())
{
piecePrice.Add(Convert.ToDecimal(context.piece.SingleOrDefault(x => x.quantity == p)?.price));
proteinPrice.Add(Convert.ToDecimal(context.protein.SingleOrDefault(x => x.name == h)?.price));
vegetablePrice.Add(Convert.ToDecimal(context.vegetable.SingleOrDefault(x => x.name == h)?.price));
wrappedPrice.Add(Convert.ToDecimal(context. wrapped.SingleOrDefault(x => x.name == f)?.price));
}
}
}
保存按钮点击处理程序:
private void button2_Click(object sender, EventArgs e)
{
List<rolls> rolls = new List<rolls>();
for (int i = 0; i < piece.Count(); i++)
{
p = piece[i];
pp = piecePrice[i];
x = protein[i];
v = vegetable[i];
f = wrapped[i];
xx = proteinPrice[i];
vv = vegetablePrice[i];
ff = wrappedPrice[i];
using (var context = new AppDbContext())
{
rolls.Add(new rolls()
{
quantity = p,
quantity_price = pp,
protein = x,
protein_price = xx,
vegetable = v,
vegetable_price = vv,
wrapped = f,
wrapped_price = ff
});
context.AddRange(rolls);
context.SaveChanges();
}
}
}
卷桌:
public class rolls
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int rollId { get; set; }
public int quantity { get; set; }
public decimal quantity_price { get; set; }
public string protein { get; set; }
public decimal protein_price { get; set; }
public string vegetable { get; set; }
public decimal vegetable_price { get; set; }
public string wrapped { get; set; }
public decimal wrapped_price { get; set; }
}
【问题讨论】:
-
异常“Cannot insert explicit value for identity column in table 'roll' when IDENTITY_INSERT is set to OFF”表示您尝试将实际值插入到自动生成的列中。跨度>
-
aggregate table roll ,,有表格、蛋白质、蔬菜和包装图表,我可以在其中获取名称和价格数据以保存到 Rolls。
标签: c# entity-framework