我正在尝试使用现有数据库创建实体框架代码优先方案。
问题是,当我运行程序时,即使我使用IQueryable<>
,也会尝试连接到数据库。请阅读代码中的评论以获取更多详细信息:
static void Main(string[] args)
{
using (SomeContext db = new SomeContext())
{
// This one does not connects to database.
// If I disable my network connection this code will still be executed
IQueryable<Activity> allActivitiesQuery = db.ActivitySet;
// This one does connects to database.
// If I disable my network connection this query will throw exception
IQueryable<Activity> filteredActivitiesQuery = db.ActivitySet
.Where(activity => !string.IsNullOrEmpty(activity.FirstProperty));
}
//If I use same context again it will not connect to database
using (SomeContext db = new SomeContext())
{
//Both statements will be executed even network connection is closed
IQueryable<Activity> allActivitiesQuery = db.ActivitySet;
IQueryable<Activity> filteredActivitiesQuery = db.ActivitySet
.Where(activity => !string.IsNullOrEmpty(activity.FirstProperty));
}
}
如何防止此行为?当我首先使用数据库并从数据库生成模型时,这种情况并未发生。
当我仅使用IQueryable<>
时,如何阻止对数据库的连接请求?
其他详细信息:
如果您需要 ,以下是我的模特:
//model
public class Activity
{
public string FirstProperty { get; set; }
public string SecondProperty { get; set; }
public string ThirdProperty { get; set; }
}
//mapping details
public class ActivityMap : EntityTypeConfiguration<Activity>
{
public ActivityMap()
{
//Primary key
..........
//Properties
.............
//Table & column mappings
.......................
}
}
//Context details
public class SomeContext : DbContext
{
static SomeContext()
{
Database.SetInitializer<SomeContext>(null);
}
public SomeContext()
: base("Name=SomeContext")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.AutoDetectChangesEnabled = false;
}
public DbSet<Activity> ActivitySet { get; set; }
// Add mapping configuration for code first POCO objects
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ActivityMap());
}
}