升级到EF 4.1后出现System.NullReferenceException

时间:2011-03-19 22:32:26

标签: asp.net-mvc-3 nullreferenceexception entity-framework-4.1

我有一个使用EF CTP5的MVC3应用程序。升级到EF 4.1后,我从这里抛出NullReferenceException

   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)

我从NuGet获得了EF 4.1位。

使用自定义初始化程序初始化数据库

    public class RecreateDatabaseInitializer : IDatabaseInitializer<DatabaseContext>
    {
        public void InitializeDatabase(DatabaseContext context)
        {
            if (ConfigurationManager.ConnectionStrings["DatabaseContextSA"] == null)
            {
                EventLog.WriteEntry("RecreateDatabaseInitializer", "Connection string 'DatabaseContextSA' doesn't exist in config file.", EventLogEntryType.Warning);
                return;
            }

            using (var ctx = new DatabaseContext("DatabaseContextSA"))
            {
                if (ctx.Database.Exists())
                    DropDatabase(ctx);

                CreateDatabase(ctx);
                InitializeDatabaseObjects(ctx);
                ctx.SaveChanges();
            }

            PopulateDatabase(context);
            context.SaveChanges();
        }
    }

PopulateDatabase()方法抛出异常。

有什么想法吗?

更新

似乎问题源于第二个DatabaseContext的实例化,以手动重新创建数据库。它必须以某种方式干扰原始背景。

1 个答案:

答案 0 :(得分:1)

我使用过Ladislav's decorator for closing opened connections但我不得不稍微修改一下。这是必需的(我相信)因为我使用sql身份验证并且有两个连接字符串(一个具有提升的权限,另一个只有读/写)。

public class ForceDeleteInitializer : IDatabaseInitializer<DatabaseContext>
{
    private readonly IDatabaseInitializer<DatabaseContext> InnerInitializer;

    public ForceDeleteInitializer(IDatabaseInitializer<DatabaseContext> innerInitializer)
    {
        this.InnerInitializer = innerInitializer;
    }

    public void InitializeDatabase(DatabaseContext context)
    {
        using (var ctx = new DatabaseContext("DatabaseContextSA"))
        {
            Database.SetInitializer<DatabaseContext>(null);
            ctx.Database.ExecuteSqlCommand("ALTER DATABASE " + ctx.Database.Connection.Database + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
        }

        this.InnerInitializer.InitializeDatabase(context);

        Database.SetInitializer<DatabaseContext>(this);
    }
}