使用DBContext显式加载不起作用/不会更改值

时间:2016-04-26 08:29:40

标签: c# entity-framework entity-framework-6

设置新的FOREIGN KEY值后,我会尝试更新我的实体。

我的(简化)实体是:

public class FirstEntity
{
    public Guid Id { get; set; }
    public Guid SecondEntityId {get; set;} // <-- this is the FK        
    public virtual SecondEntity SecondEntity { get; set; } // <-- this is the navigation property
}

public class SecondEntity 
{
    public Guid Id { get; set;}     
    public virtual ICollection<FirstEntity> FirstEntity { get; set; }
}

在我的代码中的某个时刻,我想通过将FK值设置为新值来更改FirstEntity类型对象的引用。

var theFirstEntity = DbContext.FirstEntity.Single(f => f.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));
// at this point theFirstEntity.SecondEntityId is 'e06f8909-98f9-4dc6-92ec-49d9a6aac831'

theFirstEntity.SecondEntityId = Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44"); // <-- existing Id from database
// now theFirstEntity.SecondEntityId is 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44' 
// but the reference theFirstEntity.SecondEntity is still pointing the 'old' entity with id 'e06f8909-98f9-4dc6-92ec-49d9a6aac831' 
// but it should have id 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44

现在我尝试使用

显式加载新引用
DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Load();

找到here

FirstEntity.SecondEntity与之前的System.Data.Entity.DynamicProxies.SecondEntity_XYZ保持不变。 另一方面,在查看DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Query()Parameters属性的值时,通过照看Id = 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44',查询似乎是正确的。

相反,它应该使用SecondEntity&#39; C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44&#39;来包含Id类型的正确实体。而不是&#39; old&#39;值。

1 个答案:

答案 0 :(得分:0)

您需要SaveChanges然后显式加载。

theFirstEntity = myDbContext.FirstEntity.Single(f => f.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));
theFirstEntity.SecondEntityId = Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44");

myDbContext.SaveChanges();

DbContext.Entry(theFirstEntity).Reference(t => t.SecondEntity).Load();

但是在这种情况下,只需为SecondEntity分配一个新的已加载的FirstEntity值就更方便了:

var f = myDbContext.Set<FirstEntity>().Include(p => p.SecondEntity)
    .Single(x => x.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));

var s = myDbContext.Set<SecondEntity>()
    .Single(x => x.Id == Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44"));

f.SecondEntity = s;

myDbContext.SaveChanges();