【问题标题】:updating a foreign key column in sql from C# using linq使用 linq 从 C# 更新 sql 中的外键列
【发布时间】:2018-04-25 05:57:33
【问题描述】:

我正在使用 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();
}

有什么问题? 提前谢谢!

【问题讨论】:

  • 违规的代码行是 db.SubmitChanges() 吗?
  • 没有。违规行是 product.CategoryId = categoryID;(表中的外键列) product.SupplierId = SupplierID;(表中的外键列)

标签: c# entity-framework linq


【解决方案1】:

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

对不起,我没有足够的声誉来写评论,这就是为什么将其发布为答案

【讨论】:

    【解决方案2】:

    如果导航属性已经加载了与您尝试设置的新 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多