为什么LazyLoading无法正常工作?

时间:2015-08-03 14:50:08

标签: c# entity-framework lazy-loading proxy-classes

请参阅以下代码:

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,而不是动态代理。所以,延迟加载失败。这些类显然满足了动态代理创建和延迟加载的所有要求。

为什么不起作用?

1 个答案:

答案 0 :(得分:3)

因为您的实体的类嵌套在非公共类Program中,因此EF无法为它们生成代理类。请考虑将Program的访问修饰符更改为public,或在Program之外定义您的实体类。