如何在Entity Framework OnModelCreating中运行查询 [英] How to run a query in Entity Framework OnModelCreating

查看:76
本文介绍了如何在Entity Framework OnModelCreating中运行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法如何在 OnModelCreating 中运行查询吗?

Any ideas how to run a query in OnModelCreating?

我正在尝试运行查询,然后

I am trying to run a query and then ignore a column in the entity based on that.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     var d = this.Database.SqlQuery<int?>(@"select 1 from sys.columns where Name = N'columnname' and Object_ID = Object_ID(N'tablename')").SingleOrDefault();

     if(d == null)
     {
         depEntity.Ignore(d => d.colmnname);
     }
}

我遇到以下错误:


在创建模型时不能使用上下文。如果在OnModelCreating方法内部使用上下文,或者多个线程同时访问同一上下文实例,则可能引发此异常。注意,不能保证DbContext和相关类的实例成员是线程安全的。 (有关详细信息,请参阅内部异常。)

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe. (See inner exception for details.)

System.InvalidOperationException:创建模型时不能使用上下文。如果在OnModelCreating方法内部使用上下文,或者多个线程同时访问同一上下文实例,则可能引发此异常。请注意,不能保证DbContext和相关类的实例成员是线程安全的。

System.InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.


推荐答案

我认为这两种情况都应该有两个上下文类。然后应在 Factory 内部调用查询以选择应返回其实例的类:

I think you should have two context classes for both cases. And your query should be invoked inside Factory to select class of which instance should be returned:

public class CommonContext : DbContext
{
    //common stuff...
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //common stuff...
    }
}

public class IgnoreContext : CommonContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<DepEntity>().Ignore(d => d.colmnname);
    }
}

public ContextFactory()
{
    public CommonContext CreateContext()
    {
         var ctx = new CommonContext();
         var d = ctx.Database.SqlQuery<int?>(@"select 1 from sys.columns where Name = N'columnname' and Object_ID = Object_ID(N'tablename')").SingleOrDefault();
         if(d != null)
             return ctx;             
         return new IgnoreContext();
    }
}

这篇关于如何在Entity Framework OnModelCreating中运行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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