在具有外键的分离实体上更改导航属性

时间:2016-03-21 16:44:04

标签: entity-framework foreign-keys navigation-properties

考虑以下POCO实体:

public class Produkt
{
    public int Id { get; set; }
    public int ProviderId { get; set; }
    public virtual Provider Provider { get; set; }
}

和以下代码:

Product product;
Provider provider1;
Provider provider2;
using (var context = new TestContext())
{
    provider1 = context.Provider.Add(new Provider());
    provider2 = context.Provider.Add(new Provider());
    product = context.Product.Add(new Product() { Provider = provider1 });
    context.SaveChanges();
}

// Imagine a GUI using product and provider1 and provider2 to display some data.
// Now the user changes the provider for the product.
product.Provider = provider2;

// Now the user presses the save button.
using (var context = new TestContext())
{
    context.Entry(product).State = EntityState.Modified;      // ERROR
    context.SaveChanges();
}

这里的问题是product.ProviderId没有得到更新,因为当实体没有附加到上下文时发生了更改。
一个显而易见的解决方案是保持上下文开放。然而,如果整个用户交互可能需要一段时间,这似乎是一个坏主意 另一种解决方案是手动设置ProviderId。但这很容易出错。

解决此问题的最佳方法是什么?

0 个答案:

没有答案