C# 实体框架(一对一映射)获取的依赖关系模型为空

C# 实体框架(一对一映射)获取的依赖关系模型为空,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,表dbo.用户: 用户ID, 用户名, 电子邮件, 表dbo.Client: 用户ID, 名字, 姓, 型号: public class User { public long UserId { get; set; } public string UserName { get; set; } public string Email { get; set; } public Client Client { get; set; } ... } public

表dbo.用户: 用户ID, 用户名, 电子邮件,

表dbo.Client: 用户ID, 名字, 姓,

型号:

public class User
{
    public long UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public Client Client { get; set; }
    ...
}

public class Client
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    ...
}
public virtual Client Client { get; set; }
我的数据库内容包括:

public DbSet<User> Users { get; set; }
public DbSet<Client> Clients { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                    .HasKey(x => x.UserId)
                    .HasRequired(x => x.Client).WithRequiredPrincipal();

    modelBuilder.Entity<Client>()
                    .HasKey(x => x.UserId)
                    .ToTable("Client");
}

您是否正确定义了用户的客户端属性:

public virtual Client UserClient { get; set; }
public virtual Client UserClient { get; set; }
这样做将允许EF在运行时生成一个动态代理子类,并插入代码以支持客户端属性的延迟加载。客户端属性只有在被请求时才会被填充,但会显示为它一直在那里-通过分析数据源并检查是否发出了两个单独的查询来验证这一点

您还可以检查是否在DBContext子类的构造函数中打开了延迟加载。如果缺少此选项,则默认情况下为true

Configuration.LazyLoadingEnabled = true;

如果不能做到这一点,您如何访问DBContext,您在运行什么代码?

当然,最好禁用懒散加载,由您自己处理

Configuration.LazyLoadingEnabled = false;
在获取用户时,您应该写:

context.Users.Include("UserClient").ToList();
您也应该具有正确的属性: