【发布时间】:2016-12-05 19:30:05
【问题描述】:
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SmallStore
{
public partial class AddProduct : Form
{
private db_Entities db = new db_Entities();
private Byte[] byteBLOBData;
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Description";
comboCatagory.ValueMember = "Product_Type";
comboCatagory.Invalidate();
}
private void AddProduct_Load(object sender, EventArgs e)
{
//check the data type cant cast to int dont know why
//MessageBox.Show(comboCatagory.SelectedValue.GetType().ToString());
}
private void btnUpload_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
MemoryStream memBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(memBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Product product = new Product();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
/*THIS IS THE PROBLEM*/
product.Product_Type = (int)comboCatagory.SelectedValue;
db.Products.Add(product);
db.SaveChanges();
}
}
}
我已经为这个问题绞尽脑汁 2 天了。我有一个 dbEntities 模型绑定到 Product SQL 表中的组合分类框。 Product_type 是 int 类型,description 是 varchar(MAX)。其他一切正常。当我保存“btnSave_Click”时,我得到一个无效的转换错误。谁能解释我做错了什么。我使用 c# 一周了,我来自 java 和 c/x86asm。我对.net 和实体框架非常陌生。我知道还有其他方法可以做到这一点,但我真的很喜欢 EF。谢谢朋友!我也检查了其他问题,但他们没有处理 ef 和数据绑定到组合框。
【问题讨论】:
-
产品中是否有一个名为 product.Product_Type_Id 的字段?或类似的东西?
-
没有这个表 'Product_Type' 有 ProductType 和 Description。 ProductType 是一个主键。有一个产品表也有产品类型,它与产品表中的另一个产品类型相关。两个表上的 ProductType 都是 int。
-
public int ProductType { get;放; } 公共字符串描述 { 获取;放; } 这是在 Product_Type.cs
-
我上传这段代码时出错了。
-
请检查我的新答案
标签: c# .net sql-server entity-framework relational-database