如何使用linq为实体添加两个表的单个条目

时间:2011-08-19 09:42:51

标签: c# winforms linq entity-framework linq-to-entities

enter image description here我有一个名为

的表
                    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#语言

这是我的实体图....

2 个答案:

答案 0 :(得分:1)

我假设您要首先检查输入的类别是否已经存在,并且如果有,则要重复使用它。我还假设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()之前执行。

答案 1 :(得分:0)

如果您已正确映射所有内容,则应该可以执行以下操作:

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();

希望这会有所帮助。 :)