2

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

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

如果 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 中的错误吗?也许只有我一个人,但在我看来,当您明确地预先加载一个属性时,EF 不应该在任何时候尝试延迟加载它,即使它找不到具有给定 FK 的实体。

4

0 回答 0