DbContext如何初始化自动DbSet< T>。属性? [英] How DbContext initializes automatic DbSet<T> properties?

查看:291
本文介绍了DbContext如何初始化自动DbSet< T>。属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类:

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }
}

并实例化一个新对象:

var mycontext = new MyContext();

为什么mycontext.Orders不为null?什么时候初始化的?谁初始化了它?我真的很困惑,因为基类(DbConetxt)无法访问派生类的属性,因此不可能在基对象中初始化自动属性。

Why mycontext.Orders is not null? When it was initialized? Who has initialized it? I'm really confused because the base class (DbConetxt) cannot access the derived class properties so it is not possible that the automatic property was initialized in the base object.

推荐答案

通过查看反射的代码,在构造DbContext(基类)时,它会调用DbSetDiscoveryService(内部clasS)-本质上,它使用反射来查找DbContext上的所有属性。

From looking at the reflected code, when the DbContext (the base class) is constructed it makes a call to the DbSetDiscoveryService (an internal clasS) - which essentially uses reflection to find all properties on the DbContext, and then initializes those that need initializing.

简而言之-在构造函数中使用反射。

So in short - using reflection in the constructor.

这篇关于DbContext如何初始化自动DbSet&lt; T&gt;。属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆