在 EF 4 中应用当前值 [英] ApplyCurrentValues in EF 4

查看:18
本文介绍了在 EF 4 中应用当前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 VS 2010 RC 中使用 EF 4,发现当属性为 bool 类型且新值为 false 时 ApplyCurrentValues 不起作用!!!???
当新值为 true 时它起作用.
我不知道这是一个错误还是我遗漏了什么,但我只是在处理一个非常丑陋的工作:

I just was playing with EF 4 in VS 2010 RC and just found that ApplyCurrentValues dont work when the Property is of type bool and the newly value is false !!!???
and it works when the newly value is true .
I dont know if this is a bug or I'm missing something but I just work with a very ugly work around :

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 idea or better work around?

推荐答案

您附加了一个新的 Product,其所有 bool 属性的默认值 (false).然后将这些值之一设置为 false.它不更新也就不足为奇了;你实际上并没有改变它!在我看来,您可以通过删除一些代码来解决这个问题:

You attached a new Product with the default values for all bool properties (false). You then set one of those values false. No surprise it doesn't update; you haven't actually changed it! It seems to me you could solve this by removing some of your code:

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

即使你不喜欢这个,试试看是否有效.

Even if you don't like this, try it and see if it works.

现在在我看来,您一开始就试图避免加载产品.但是这样做会破坏您的代码.因此,尽管我对尝试优化"更新(您正在此处加载一条记录,并且更新发生的频率远低于选择)提出质疑,但让我们同意从一些有效的开始.

Now seems to me that you are trying to avoid loading the product in the first place. But doing so broke your code. So although I questions attempting to "optimize" an update (you are loading one record here, and updates happen a lot less often then selects), let's agree to start with something which works.

如果这有效,它会告诉您如果您坚持避免加载产品进行更新需要做什么:您需要将所有属性标记为已修改.

If this works, it tells you what you need to do if you insist on avoiding loading the product for update: you need to mark all properties as modified.

这篇关于在 EF 4 中应用当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆