在Entity Framework中加载附加对象的属性值

时间:2015-12-09 19:41:57

标签: .net entity-framework

我有一个包含1对1关系的对象。

public class Container
{
    public virtual Foo Property { get; set; }
}

public class Foo 
{
    public int Id {get; set;}
    public string Name {get; set;}
}

假设我们在数据库中保存了两个不同的Foo类实例,并且在初始状态Container:s Property设置为Foo1。现在我想将该属性更改为Foo2。我是这样做的:

public void SomeMethod(Container container) 
{
    container.Property = new Foo() {
        Id = 2 // Note that this Foo (that is, Foo2) already exists in the database, I just want to change the reference.
    };

    DbUpdate(container)
    DbUpdate.SaveChanges();

    var name = container.Property; // Is null because the properties has not been loaded
}

public void DbUpdate(Container container)
{
    context.Foos.Attach(container.Property);

}

这个问题是没有加载Foo2的属性。我可以改为使用这个方法:

public void DbUpdate(Container container)
{
    context.Foos.Attach(container.Property);
    context.Entry(container.Property).Reload(); // Explicitly reload the entity

}

解决了这个问题,但是,如果没有给定Id的Foo,那么Property(Container.Property)将被设置为null。

是否有其他方法可以加载附加实体的属性值?

修改

为了澄清我的问题,我正在添加我当前不满意的解决方案 因为它需要额外往返数据包。

public void DbUpdate(Container container)
{
    if(context.Entry(container.Property).State == EntityState.Added)
    {
        if(context.Foos.Any(x => x.Id == container.Property.Id))
        {
            context.Foos.Attach(container.Property);
            context.Entry(container.Property).Reload(); // Explicitly reload the entity
        }
    }
}

0 个答案:

没有答案