访问Eager加载的属性为null会导致延迟加载

时间:2013-10-09 19:33:11

标签: properties entity-framework-5 lazy-loading eager-loading objectcontext

我已经在实体上加载了一个属性。

如果该属性的FK引用指向不存在的项(即值-1),则(自然)不加载该属性。 但是:出于某种原因,当我尝试访问/检查代码中属性的值时,EF仍尝试访问databasecontext并执行此属性的延迟加载。

如果FK-reference是现有的FK-Id,那么一切正常。

public Tbl_Car GetCar(int id){
    Tbl_Car car = null;
    using (MyContext context = new MyContext())
    {
        //Explicitly tell EF not to use lazyloading seems to be the only way
        //context.Configuration.LazyLoadingEnabled = false;

        car = context.Tbl_Car
            .Include("Owner")
            .Where(x => x.Id=id)
        .SingleOrDefault();

    }
    return car;
}

public void DisplayCar(){
    Tbl_Car car=GetCar(1234);

    //I need to check if Owner is null before accessing properties.
    //For some reason lazy loading kicks in and starts complaining about missing 
    //objectcontext
    //NOTE: This only occurs if car.OwnerId is set to a nonexistent entity, i.e -1
    //If car.ownerId=<null> or the id of a owner which existing, all is ok
enter code here
    if (car.Owner!=null){
        Console.WriteLine(car.Owner.Name);  //dont get this far
    }
}

此行为是EF中的错误吗? 也许只是我,但在我看来,当你明确地急切加载一个属性时,即使它找不到具有给定FK的实体,EF也不应该在任何时候尝试延迟加载它。

0 个答案:

没有答案