Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.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没有';t延迟加载相关对象_C#_Entity Framework - Fatal编程技术网

C# EntityFramework没有';t延迟加载相关对象

C# EntityFramework没有';t延迟加载相关对象,c#,entity-framework,C#,Entity Framework,我开始使用实体框架 我已经修改了源代码 用户: +--------+-------+ | UserID | Name | +--------+-------+ | 1 | Vasya | | 2 | Petya | | 3 | Masha | +--------+-------+ 当我添加ctx.Entry(account.Reference)(p=>p.User.Load())时beforeConsole.WriteLine它开始工作正常,但我想使用延迟加载

我开始使用实体框架

我已经修改了源代码

用户

+--------+-------+
| UserID | Name  |
+--------+-------+
|      1 | Vasya |
|      2 | Petya |
|      3 | Masha |
+--------+-------+
当我添加
ctx.Entry(account.Reference)(p=>p.User.Load())时
before
Console.WriteLine
它开始工作正常,但我想使用延迟加载

这两个数据库都是从源代码自动生成的(我相信这叫做代码优先)


有什么区别?我做错了什么?

您需要立即加载相关实体


有关如何执行此操作的优秀文章,请参阅。

将类的作用域更改为public,它应该可以工作。

在MS SQL中,两个表都定义了主键吗?@BishnuPaudel,是的,Accounts表也有
FK
FK\u dbo.Accounts\u dbo.Users\u UserId
,为什么我不能使用延迟加载?根据本文的说法,虚拟机默认情况下是启用的,这就是答案。谢谢你,我可以帮你:)。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new DataBaseContext())
            {
                foreach (var account in ctx.Accounts)
                {
                    Console.WriteLine(account.User.Name); // NullRef here
                }
            }
        }
    }



    class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public virtual List<Account> Accounts { get; set; }

    }

    class Account
    {
        public int AccountId { get; set; }

        public int UserId { get; set; }
        public virtual User User { get; set; }
    }

    class DataBaseContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Account> Accounts { get; set; }
    }
}
+-----------+--------+
| AccountId | UserID |
+-----------+--------+
|         1 |      2 |
|         2 |      2 |
+-----------+--------+
+--------+-------+
| UserID | Name  |
+--------+-------+
|      1 | Vasya |
|      2 | Petya |
|      3 | Masha |
+--------+-------+