为什么延迟加载不起作用?

Why is LazyLoading not working?

请看下面的代码:

class Program
{
    public class Request
    {
        public virtual int RequestId { get; set; }
        public virtual int LastStatus { get; set; }
        public virtual RequestType RequestType { get; set; }

        [InverseProperty("Request")]
        public virtual MembershipRequest MembershipRequest { get; set; }
        [InverseProperty("Request")]
        public virtual CodingRequest CodingRequest { get; set; }
    }

    public class MembershipRequest
    {
        [Key, ForeignKey("Request")]
  public virtual int RequestId { get; set; }
        public virtual Request Request { get; set; }
        public virtual string CompanyName { get; set; }
    }

    public class CodingRequest
    {
        [Key, ForeignKey("Request")]
        public virtual int RequestId { get; set; }
        public virtual Request Request { get; set; }
        public virtual string ProductName { get; set; }
    }

    public enum RequestType
    {
        MembershipRequest,
        CodingRequest
    }

    public class Context: DbContext
    {
        public Context()
            : base("ConnectionString")
        {

        }

        public DbSet<Request> Requests { get; set; }
        public DbSet<MembershipRequest> MembershipRequests { get; set; }
        public DbSet<CodingRequest> CodingRequests { get; set; }
    }

    static void Main(string[] args)
    {
        Insert();
        Select();
    }

    private static void Select()
    {
        using (var context = new Context())
        {
            foreach (var request in context.Requests.ToList())
            {
                Console.WriteLine(request.RequestType == RequestType.CodingRequest 
                    ? request.CodingRequest.ProductName : request.MembershipRequest.CompanyName);
                      //null reference here^
            }
            Console.ReadLine();
        }
    }

    private static void Insert()
    {
        using (var context = new Context())
        {
            var r1 = new Request
            {
                LastStatus = 1,
                RequestType = RequestType.MembershipRequest,
                MembershipRequest = new MembershipRequest
                {
                    CompanyName = "company1"
                }
            };
            context.Requests.Add(r1);

            var r2 = new Request
            {
                LastStatus = 2,
                RequestType = RequestType.CodingRequest,
                CodingRequest = new CodingRequest
                {
                    ProductName = "Product2"
                }
            };
            context.Requests.Add(r2);
            context.SaveChanges();
        }
    }
}

在foreach语句中,request对象是Request类型,不是动态代理。因此,延迟加载失败了。 类 显然满足动态代理创建和延迟加载的所有要求。

为什么不起作用?

因为您的实体的 classes 嵌套在非 public class Program 中,因此 EF 无法为它们生成代理 classes .考虑在 Program.

之外更改您的 Program's access modifier to public or define your entities' classes