[英]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
我有一個帶有文本框的新表格,例如
txtprodname
txtproddescrip
txtproductprice
picturebox1
txtcategoryname
我正在嘗試通過使用以下代碼將新產品添加到producttable中
我正在使用實體框架。
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將類別名稱添加到類別表中.......
如何將類別名稱添加到類別表並使用我輸入的類別名稱更新產品表...
如何使用輸入的名稱和添加到產品表中的新產品來更新產品表中的類別ID
任何人都可以幫忙....
我正在使用Winforms .....和C#語言
這是我的實體圖。
我假設您要首先檢查輸入的類別是否已經存在,並且想要重復使用。 我還假設tsgentity
是您的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()
之前,應執行以上代碼。
如果正確映射了所有內容,則應該能夠執行以下操作:
var pd = new Product();
//Set properties of product
var c = new Category { Name = txtCategoryName.Text, Description = txtCategoryDescription.Text };
pd.Category = c;
tsgentity.AddToproducts(pd);
tsgentity.SaveChanges();
希望這可以幫助。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.