Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EntityFramework显式加载不会检索所有实体_C#_Entity Framework_Lazy Loading - Fatal编程技术网

C# EntityFramework显式加载不会检索所有实体

C# EntityFramework显式加载不会检索所有实体,c#,entity-framework,lazy-loading,C#,Entity Framework,Lazy Loading,我有两个类(用户和设备),定义如下 public class User { public int UserId { get; set; } public virtual ICollection<Device> Devices { get; set; } ... } public class Device { public int UserId; public virtual User User { get; set; } ... }

我有两个类(用户和设备),定义如下

public class User {
    public int UserId { get; set; }
    public virtual ICollection<Device> Devices { get; set; }
    ...
}

public class Device {
    public int UserId;
    public virtual User User { get; set; }
    ...
}
我正在尝试检索与用户帐户关联的所有设备。

我试过用两种不同的方法来做这件事

方法#1-调用用户关联属性上的加载

using (MyDbContext dbContext = new MyDbContext())
{
    // performing some database operations ...

    var user = dbContext.Users.Find(8);

    // do some operations 

    if (user.Devices == null or user.Devices.Count() ==0)
    dbContext.Entry(user).Collection(u => u.Devices).Load();

    var devices = user.Devices;
}
方法#2-使用where从设备集检索

using (MyDbContext dbContext = new MyDbContext())
{
    // performing some database operations ...

    var user = dbContext.Users.Find(8);

    // do some operations 

    if (user.Devices == null or user.Devices.Count() ==0)        
    var devices = dbContext.Devices.Where(d => d.UserId == user.UserId).ToList();
}
出于某种原因,方法1并不总是检索所有设备,但方法2检索所有设备!有人能解释一下我做错了什么吗

我启动了SQL Server Profiler,以查看我是否做错了什么。两种方法生成的查询是相同的。所以我真的很困惑我做错了什么

有人能解释一下我做错了什么吗

我无法解释为什么您正在体验您正在体验的内容,但我个人不使用
Find()
Load()
,因为这些方法在如何使用本地上下文缓存方面非常复杂。因此,我推荐以下查询:

var user = dbContext.Users
  .Include(u => u.Devices);
  .FirstOrDefault(u => u.id = 8);
因为您只检索一个用户,所以没有问题。此查询将在单个语句中使用用户和与用户关联的所有设备填充上下文

如果您真的需要一个单独的变量来处理之后的所有设备:

var devices = user.Devices;
关于我的答案,重要的一点是,因为我通常在web环境中处理实体框架,所以我的代码不断地创建/处理上下文,所以实体框架上的本地缓存几乎是无用的。对于非无状态应用程序(Winforms/WPF),这可能不是最佳解决方案

根据您的评论更新

以后是否有其他方式装载

如前所述,您可以使用:

var devices = dbContext.Devices
  .Where(w => w.UserId == 8);

(请注意,这不会对数据源执行查询)。

什么版本的Entity Framework?我是Entity Framework的新手,所以我还不完全熟悉不同的表达式。是否包括检索用户id为8的所有设备?还是从数据库中检索所有设备,然后过滤用户id为8的设备?第一个命题是正确的。为了说服自己,请使用@ParthShah,我还更新了我的答案,使之更具体。@ErikPhilips我喜欢你给我的答案,但问题是我在检索用户时并不总是需要加载设备。(很抱歉,我的代码示例有误导性。)以后还有其他加载方式吗?var devices=dbContext.devices.Where(w=>w.UserId==8)
var devices = dbContext.Devices
  .Where(w => w.UserId == 8);