使用linq从C#更新sql中的外键列

时间:2018-04-24 20:15:11

标签: c# entity-framework linq

我正在使用Linq在C#中创建一个Windows窗体应用程序。我正在尝试更新外键列,但我继续收到错误:

  

“由于对象的当前状态,操作无效。”

错误的消息框指向该行:

throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();

我使用以下方法尝试更新:

//Updates a Product
public void UpdateProduct(int productID, string productName, int categoryID, int supplierID, bool priceType, decimal costPrice, decimal retailPrice, bool inStock)
{
    Product product = (from p in db.Products
                       where p.ProductId == productID
                       select p).Single();

    product.Name = productName;
    product.CategoryId = categoryID;
    product.SupplierId = supplierID;
    product.PriceType = priceType;
    product.CostPrice = costPrice;
    product.RetailPrice = retailPrice;
    product.Stock = inStock;

    db.SubmitChanges();
}

有什么问题? 提前谢谢!

2 个答案:

答案 0 :(得分:0)

可能与这些有关 Linq to SQL ForeignKeyReferenceAlreadyHasValueExceptionHow to change the value of associated field

抱歉,我没有足够的声誉来撰写评论,这就是将此作为答案发布的原因

答案 1 :(得分:0)

如果导航属性已加载了与您尝试设置的新ID不匹配的值,则会出现错误。

尝试设置导航属性,而不是设置ID值,如下所示:

public void UpdateProduct(int productID, string productName, int categoryID, int supplierID, bool priceType, decimal costPrice, decimal retailPrice, bool inStock)
{
    Product product = (from p in db.Products
                       where p.ProductId == productID
                       select p).Single();

    Category cat = (from c in db.Categories
                    where c.CategoryId == categoryID
                    select c).FirstOrDefault();

    Supplier sup = (from s in db.Suppliers
                    where s.SupplierID == supplierID
                    select s).FirstOrDefault();

    product.Name = productName;
    product.Category = cat;
    product.Supplier = sup;
    product.PriceType = priceType;
    product.CostPrice = costPrice;
    product.RetailPrice = retailPrice;
    product.Stock = inStock;

    db.SubmitChanges();
}