gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:12 26 4
gpt4 key购买 nike

请看下面的代码:

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

为什么它不起作用?

最佳答案

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

关于c# - 为什么延迟加载不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com