LINQ to SQL – Operation is not valid due to the current state of the object

Posted by | November 09, 2010 | ASP.NET | 5 Comments
asp-dot-net-logo

I have been working with LINQ to SQL for a little while now. When I attempt to update a entity property, I get the following exception: “Operation is not valid due to the current state of the object” which gets fired on ForeignKeyReferenceAlreadyHasValueException().

I was trying to assign a value to the foreign key property. There are two properties (references or lists of other objects) and the foreign keys which are used to define this relationship in the database. If foreign key fields and association properties are not equal, LINQ to SQL will throw this exception when you attempt to submit changes. Because it doesn’t know which is the correct value, the one in the foreign key field or the one on the other side of the relationship. The code-generated objects will automatically keep the foreign keys in sync with any association (foreign keys) property when you assign the association property a value.

So the best way to assign the relationship by changing the association property and not the foreign keys. The only time a foreign key field is used as the value is when there is either no association property defined on the object using that field as a key or the association property was never assigned a value.

MSDN document for ForeignKeyReferenceAlreadyHasValueException:
http://msdn.microsoft.com/en-us/library/system.data.linq.foreignkeyreferencealreadyhasvalueexception.aspx

avatar

About Farid

Creative web developer/designer, big fan of HTML5, CSS3 and client-side development. Software developer at Allegra Strategies London.

  • http://www.blogtext.org/weightlosscalcul/article/229299.html?calculateweightloss me

    cool

  • hiren

    hello,
    When i set the association property and foreign key value than record will be inserted new on parent table and new id reference added to child table

  • Yatin Chauhan

    How can we Set the asspcoation property ???????
    here is my method

    public void updateProduct(Product sProductsMaster)
    {
    Product updateObj = (from sc in _dbPoojaraTele.Products
    where sc.ID.Equals(sProductsMaster.ID)
    select sc).FirstOrDefault();

    PopulateModel(sProductsMaster, updateObj);
    _dbPoojaraTele.SubmitChanges();
    }

  • Farid Hayati

    @Yating

    using (AdventureWorksContext db = new AdventureWorksContext())
    {
    	//retrieve product
    	Product product = (from p in db.Products
    			   where p.ProductID == 850
    			   select p).FirstOrDefault();
     
    	//retrieve product model
    	ProductModel model = (from m in db.ProductModels
    			      where m.ProductModelID == 13 
    			      select m).FirstOrDefault();
     
    	// set the asspcoation property of product
    	product.ProductModel = model;
     
    	//save changes 
    	db.SubmitChanges();
    }
  • Pingback: URL