EntityFramework不会懒惰地加载相关对象

时间:2014-03-07 04:05:14

标签: c# entity-framework

我开始使用Entity Framework。

我的代码是从this example

修改的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace CodeFirstNewDatabaseSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext()) 
            {
                foreach (var post in db.Posts)
                {
                    Console.WriteLine(post.Blog.Name);
                }
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }
}

它工作正常。但我自己写了另一段代码:

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; }
    }
}

我的代码结果是NullReferenceException

使用MS SQL Server Management Studio,我看到了表的内容:

Accounts

+-----------+--------+
| AccountId | UserID |
+-----------+--------+
|         1 |      2 |
|         2 |      2 |
+-----------+--------+

Users

+--------+-------+
| UserID | Name  |
+--------+-------+
|      1 | Vasya |
|      2 | Petya |
|      3 | Masha |
+--------+-------+

当我在ctx.Entry(account).Reference(p => p.User).Load();之前添加Console.WriteLine它开始正常工作,但我想使用延迟加载

两个数据库都是从源代码自动生成的(我称之为Code First)。

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

2 个答案:

答案 0 :(得分:1)

更改课程&#39;范围公开,它应该工作。

答案 1 :(得分:0)

您需要急切加载相关实体。

有关如何执行此操作的优秀文章,请参阅http://msdn.microsoft.com/en-us/data/jj574232.aspx

相关问题