c# - 向数据库表添加新记录时出现异常未处理
问题描述
c# 新手,我正在尝试将新记录保存到数据库表“ProductTbl”中。该程序首先运行具有多个输入的 Windows 窗体,即描述、价格、类别和图像。然后单击保存按钮,该按钮应将新记录保存到表中。以下是 savebtn 点击代码。
private void btnSave_Click(object sender, EventArgs e)
{
ProductTbl product = new ProductTbl();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
product.ProductType = (int)cboCategory.SelectedValue;
cse.AddToProductTbl(product);
cse.SaveChanges();
MessageBox.Show("Record Saved");
}
继 cse.AddToProductTbl(product); 标记,是数据库上下文中的这段代码。
internal void AddToProductTbl(ProductTbl product)
{
throw new NotImplementedException();
}
我不断收到同样的错误;
System.NotImplementedException: 'The method or operation is not implemented.'
任何帮助,将不胜感激,
提前致谢,雅各布
解决方案
@雅各布鲁塞尔16。为了向数据库表“ProductTbl”插入和保存新记录,您可以使用现有的Add方法(Context.TableName.Add())来添加记录并删除 AddToProductTbl(ProductTbl product) 方法。您可以参考下面的代码示例。
更新:
1.在数据库表中添加一个图像列,并将其类型设置为varbinary(MAX)。
在Form.cs[Design]中添加pictureBox控件,双击添加pictureBox1_Click事件。
修改 Form.cs 中的代码。
Form.cs 中的代码:
ProductTblContext cse = new ProductTblContext ();
private void btnSave_Click(object sender, EventArgs e)
{
ProductTbl product = new ProductTbl ();
product.Id = int.Parse(txtId.Text);
product.Name = txtProduct.Text;
product.price = decimal.Parse(txtPrice.Text);
product.description = txtDescription.Text;
product.type = Convert.ToInt32(comboBox1.SelectedValue.ToString());
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Dispose();
product.image = ms.ToArray();
cse. ProductTbl.Add(product);
cse.SaveChanges();
MessageBox.Show("record saved");
}
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "@.jpg|*JPG|@.Png|*png|@Gif|*.gif|@.All files|*.*";
DialogResult dr = openFileDialog.ShowDialog();
if (dr == DialogResult.OK)
{
FileStream fs = new FileStream(openFileDialog.FileName,FileMode.Open,FileAccess.Read);
Image im = Image.FromStream(fs);
pictureBox1.Image = im;
}
}
ProductTblContext相关代码如下:
public partial class ProductTblContext: DbContext
{
public ProductTblContext()
: base("name= ProductTblContext")
{
}
public virtual DbSet<ProductTbl> ProductTbl{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductTbl>()
.Property(e => e.Name)
.IsFixedLength();
modelBuilder.Entity<ProductTbl>()
.Property(e => e.price)
.HasPrecision(18, 0);
modelBuilder.Entity<ProductTbl>()
.Property(e => e.description)
.IsFixedLength();
}
}
推荐阅读
- javascript - JS,如何调用无名列表
- ios - Xcode 无法生成 Swift UI 预览 - 由于内部错误导致构建中止:planningFailed
- sql - 对 SQL Server 附加本地数据库大小的困惑
- r - 使用路径变量在 R Markdown 中插入图像
- html - 如何使用 CSS Grid 实现这种布局?
- python - 通过传递列表/元组来更改 pandas matplotlib 条形图中的条形颜色
- ios - 仅在 iOS 14 中,我的 uiwebview 在 stringByEvaluatingJavaScriptFromString 中崩溃
- javascript - 如何将字段添加到没有属性的数组反应js
- mysql - mysql中使用重复循环的素数生成器
- flutter - 如何在颤动的嵌套行/列中使用文本溢出?