In EF 4, use ApplyCurrentValues.

.net entity-framework visual-studio-2010

Question

I just discovered when experimenting with EF 4 in Visual Studio 2010 RC that ApplyCurrentValues doesn't function when the Property is of type bool and the updated value is false!!!
and when the newest value is true, it functions.
I'm not sure whether this is a problem or I'm missing something, but I have to make due with this rather unsightly workaround:

public void UpdateProduct(Product updatedProduct)
    {
        using (model)
        {
            model.Products.Attach(new Product { ProductID = updatedProduct.ProductID });
            model.Products.ApplyCurrentValues(updatedProduct);
            Product originalProduct = model.Products.Single(p => p.ProductID == updatedProduct.ProductID);
            originalProduct.Discontinued = updatedProduct.Discontinued;
            model.SaveChanges();

        }

    }

Any suggestions for a better solution?

1
6
4/10/2010 5:49:54 PM

Accepted Answer

You added a freshProduct using the bool attributes' default values (false). Afterward, you set one of those variables to false. It's understandable that it doesn't update because you haven't made any changes. By deleting part of your code, it appears like you might fix this:

public void UpdateProduct(Product updatedProduct)
{
    using (model)
    {
        Product originalProduct = model.Products.Single(p => p.ProductID == updatedProduct.ProductID);
        model.Products.ApplyCurrentValues(updatedProduct);
        model.SaveChanges();
    }
}

Try it even if you don't like it to see if it helps.

It now seems to me that you are attempting to prevent loading the product at all. But doing so broke your code. Therefore, let's agree to start with something that works even if I have my doubts about trying to "optimize" an update (you are loading one record here, and updates happen far less often than selections).

If it succeeds, it will inform you what to do if you're determined to prevent loading the update for the product: Mark each property as changed..

20
2/16/2010 2:19:08 PM

Popular Answer

Modified:

public void UpdateProduct(Product updatedProduct)
{
    using (model)
    {
        model.Products.Single(p => p.ProductID == updatedProduct.ProductID);
        model.Products.ApplyCurrentValues(updatedProduct);
        model.SaveChanges();
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow