首页 > 解决方案 > 向数据库表添加新记录时出现异常未处理

问题描述

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.'

任何帮助,将不胜感激,

提前致谢,雅各布

标签: c#visual-studio

解决方案


@雅各布鲁塞尔16。为了向数据库表“ProductTbl”插入和保存新记录,您可以使用现有的Add方法(Context.TableName.Add())来添加记录并删除 AddToProductTbl(ProductTbl product) 方法。您可以参考下面的代码示例。

更新:

1.在数据库表中添加一个图像列,并将其类型设置为varbinary(MAX)。

  1. 在Form.cs[Design]中添加pictureBox控件,双击添加pictureBox1_Click事件。

  2. 修改 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();
    }
}

结果如图所示: 在此处输入图像描述


推荐阅读