我读过文章EntityFramework如何将表达式转换为SQL查询。有趣的部分是EF预处理表达式树如何从树中排除闭包和本地属性,并用实际值替换它们。这是我的代码。我试图找出何时以及在何种情况下评估本地属性。但我无法用调试器捕捉到这一刻。但我看到一些状态变化。
private bool _called1;
private bool _called2;
protected bool Noob1 {
get {
Debugger.Break(); // never works
_called1 = true; // changes to true sometimes
return true;
}
}
public bool Noob2 {
get {
Debugger.Break(); // never works
_called2 = true; // changes to true sometimes
return false;
}
}
public ActionResult Index() {
var dn = new ApplicationDbContext();
var q1 = dn.Heros.Where(h => h.IsNoob == Noob1);
dn.Heros.Where(h => h.IsNoob == Noob2);
var result = this.GetType().GetMethod("About").Invoke(this, null); // to test breakpoint inside About action. call it using reflection
return Content(String.Format("c1={0}; c2={1}", _called1, _called2));
}
public ActionResult About()
{
// if i place breakpoint here is fires, so no problem with debugger and invoking through reflection
ViewBag.Message = "Your application description page.";
return View();
}
每次运行此代码_called1或_called2都是如此。有时他们都是真的。但断点在我的属性中不起作用。这怎么可能?为什么_called1和_called2改变它们的值如此不可预测?当EF预处理表达式树时,如何查看thead callstack?
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Hero> Heros { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
P.S。 写完这个问题之后,我明白了我写的Heros设置为错误的DbContext。但我认为这不会导致问题。