我有以下结构:
public class A{}
public Class B:A
{
public virtual C { get; set;}
}
public Class C{}
public Class Context:DbContext
{
public DbSet<A> As { get; set; }
public DbSet<C> Cs { get; set; }
}
当我想加载任何对象b
时,此对象的属性C
为null。在数据库中,列C在表A
中有一个id。可以毫无问题地加载其他int
或string
属性。
using(var ctx = new Context())
{
B b = ctx.As.FirstOrDefault() as B;
}
我可以使用延迟加载解决这个问题吗?使用Eagerly加载我有一个问题要包含属性B
,因为我有一个列表List<A> someAs
,其中一些项目来自B
类型。
我试图让这个例子尽可能简单。请告诉我提供更多信息。
答案 0 :(得分:1)
如果您想急切加载子类的属性,则必须显式查询子类:
ctx.As.OfType<B>().Include(b => b.Cs).FirstOrDefault();
答案 1 :(得分:0)
您可以继续使用延迟加载,并指定使用.Include()
加载子关系。
例如:
using (var context = new BloggingContext())
{
// Load all blogs and related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
// Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault();
// Load all blogs and related posts
// using a string to specify the relationship
var blogs2 = context.Blogs
.Include("Posts")
.ToList();
// Load one blog and its related posts
// using a string to specify the relationship
var blog2 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include("Posts")
.FirstOrDefault();
}