sqlite EF DbUpdateException

时间:2014-05-18 17:38:47

标签: c# entity-framework sqlite ef-code-first

我正在尝试使用下面定义的简单控制台应用程序来学习SQLite和实体框架。当我在VS中运行它时,我在执行context.SaveChanges()时得到如下所示的异常。我需要帮助解决这个问题。

using System;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Reflection;

namespace EntityFrameworkConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var sb = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            sb.DataSource = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "test.db");
            sb.ForeignKeys = true;
            sb.BinaryGUID = true;
            sb.DateTimeFormat = SQLiteDateFormats.ISO8601;
            sb.DateTimeKind = DateTimeKind.Local;
            sb.ToFullPath = true;

            using (var context = new BloggingContext(new SQLiteConnection(sb.ConnectionString)))
            {

                context.Blogs.Add(new Blog { Name = "Yet Another Blog #1" });

                context.SaveChanges();

                var blogs = (from b in context.Blogs
                             orderby b.Name
                             select b).ToList();

            }
        }

    }
}

using System.Data.Common;
using System.Data.Entity;

namespace EntityFrameworkConsoleApplication1
{
    [DbConfigurationType(typeof(MyConfiguration))]
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbConnection c):base(c,true)
        {
        }

        public DbSet<Blog> Blogs { get; set; }
    }
}

namespace EntityFrameworkConsoleApplication1
{
    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
    }
}

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Common;
using System.Data.SQLite;
using System.Data.SQLite.Linq;
using System.Reflection;

namespace EntityFrameworkConsoleApplication1
{
    public class MyConfiguration : DbConfiguration
    {
        public MyConfiguration()
        {
            SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
            SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
            Type t = Type.GetType(
                       "System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6");
            FieldInfo fi = t.GetField("Instance", BindingFlags.NonPublic | BindingFlags.Static);
            SetProviderServices("System.Data.SQLite", (DbProviderServices)fi.GetValue(null));
        }
    }
}
  

System.Data.Entity.Infrastructure.DbUpdateException未处理
  _HResult = -2146233087 _message =更新条目时发生错误。有关详细信息,请参阅内部异常的HResult = -2146233087
  IsTransient = false Message =更新时发生错误   条目。有关详细信息,请参阅内部异常来源=的EntityFramework   堆栈跟踪:          在System.Data.Entity.Internal.InternalContext.SaveChanges()          在System.Data.Entity.Internal.LazyInternalContext.SaveChanges()          在System.Data.Entity.DbContext.SaveChanges()          at c:\ Users \ John \ Documents \ Visual Studio中的EntityFrameworkConsoleApplication1.Program.Main(String [] args)   2013 \项目\ EntityFrameworkConsoleApplication1 \ EntityFrameworkConsoleApplication1 \的Program.cs:行   33          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          at System.Threading.ThreadHelper.ThreadStart()InnerException:System.Data.Entity.Core.UpdateException          _HResult = -2146233087          _message =更新条目时发生错误。有关详细信息,请参阅内部异常          的HResult = -2146233087          IsTransient = FALSE          消息=更新条目时发生错误。有关详细信息,请参阅内部异常          来源=的EntityFramework          堆栈跟踪:               在System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()               在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator)   UT)               在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update [T](T   noChangesResult,Func 2 updateFunction, Boolean throwOnClosedConnection) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Boolean throwOnClosedConnection) at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__33() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func 1   func,IDbExecutionStrategy executionStrategy,Boolean   startLocalTransaction,Boolean releaseConnectionOnSuccess)               在System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions)   选项,IDbExecutionStrategy executionStrategy)               在System.Data.Entity.Core.Objects.ObjectContext。&lt;&gt; c__DisplayClass28.b__25()               at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute [TResult](Func 1 operation) at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException: System.Data.SQLite.SQLiteException _HResult=-2147467259 _message=SQL logic error or missing database no such table: Blogs HResult=-2147467259 IsTransient=false Message=SQL logic error or missing database no such table: Blogs Source=System.Data.SQLite ErrorCode=1 StackTrace: at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain) at System.Data.SQLite.SQLiteCommand.BuildNextCommand() at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index) at System.Data.SQLite.SQLiteDataReader.NextResult() at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave) at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8() at System.Data.Entity.Infrastructure.Interception.InternalDispatcher 1.Dispatch [TInterceptionContext,TResult](Func 1 operation, TInterceptionContext interceptionContext, Action 1   执行,行动1 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary 2   identifierValues,List`1 generatedValues)                    在System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()               的InnerException:

1 个答案:

答案 0 :(得分:0)

我猜您已经更改了模型,或者您在第一次创建数据库后添加了博客。 在BloggingContext的Constractor中写下这个:

Database.SetInitializer<BloggingContext>(new DropCreateDatabaseIfModelChanges<BloggingContext>());

希望它有效。