如何使用linq向实体添加两个表的单个条目 [英] how do add a single entry for two tables using linq to entities
问题描述
我有表
product
product_id
product_Name
product_Price
product_Description
product_image
category_id
another table category
category_id
category_name
我有一个新的表单与文本框如
i have a new form with textboxes like
txtprodname
txtproddescrip
txtproductprice
picturebox1
txtcategoryname
我正在尝试通过使用以下代码将新产品添加到producttable中
i am trying to add the new product to producttable by using following code
我正在使用实体框架。
public byte[] imageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
private void btnSave_Click(object sender, EventArgs e)
{
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
product pd = new product();
pd.product_Name = txtprodname.Text;
decimal price = Convert.ToDecimal(txtproductprice.Text);
pd.product_Price = price;
pd.product_Description = txtproddescrip.Text;
pd.product_Image = bit;
tsgentity.AddToproducts(pd);
tsgentity.SaveChanges();
this.Close();
}
我正在尝试将新产品添加到产品表中。但我没有任何想法如何添加类别名称到类别表.......通过使用linq
I am trying to add new product to the product table .. but i dont have any idea how to add the category name to category table .......by using linq
我如何添加类别名称到类别表并更新我输入的类别名称的产品表...
how do i add category name to category table and update the product table with category name that i have entered...
如何更新产品表中的类别ID,并添加新产品产品表
how do update the category id in product table with this name entered along with the new product added to the product table
可以任何一个帮助这个....
can any one help on this ....
我正在使用winforms ... ..和c#语言
i am using winforms .....and c# language
这是我的实体图....
this is my entity diagram....
推荐答案
我假设你想先检查输入的类别是否已经存在,并希望重用它。我也假设 tsgentity
是你的DbContext:
I assume you want to first check if the entered category already exists and want to reuse it if it does. I also assume tsgentity
is your DbContext:
string categoryName = category_name.Text;
Category category = tsgentity.Categories.FirstOrDefault(c => c.category_name == categoryName );
if (category == null)
category = new Category() { category_name = categoryName };
pd.category = category;
tsgentity.Categories.Add(category);
上述代码应该在运行 tsgentity.SaveChanges()
。
这篇关于如何使用linq向实体添加两个表的单个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!