本文介绍了代码首先与实体框架在保存时会引发DbUpdateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Visual Studio C#项目中创建我的第一个数据库,并向该数据库添加一个实体。我还没有设法做到这一点。当尝试时,在$ code> DbContext 调用 SaveChanges()时,我会得到一个 DbUpdateException code>。

I am trying to create my first database in a Visual Studio C# project and add an entity to this database. I have not yet managed to do so. When trying, I will get a DbUpdateException when calling SaveChanges() on the DbContext.

我正在尝试保存以下实体:

I am trying to save the following entity:

public class TVSeriesReference : Reference
{
}

TVSeriesReference 只能继承参考

public class Reference
{
    /// <summary>
    /// ID of the reference.
    /// </summary>
    public int Id { get; set;  }

    /// <summary>
    /// Reference to the element in theTVDB.
    /// </summary>
    public int TheTVDBId { get; set; }

    /// <summary>
    /// Whether or not the reference has been marked as watched.
    /// </summary>
    public bool IsWatched { get; set; }
}

我正在使用以下上下文:

I am using the following context:

public class Library : DbContext
{
    /// <summary>
    /// Constructor using the base constructor.
    /// This constructor names the database "Library".
    /// </summary>
    public Library() : base("Library")
    {
    }

    /// <summary>
    /// Set of TVSeriesReferences stored in the database.
    /// </summary>
    public DbSet<TVSeriesReference> TVSeriesReferences { get; set; }

    /// <summary>
    /// Set of SeasonReferences stored in the database.
    /// </summary>
    public DbSet<SeasonReference> SeasonReferences { get; set; }

    /// <summary>
    /// Set of EpisodeReferences stored in the database.
    /// </summary>
    public DbSet<EpisodeReference> EpisodeReferences { get; set; }
}

这是我如何尝试创建并将实体保存到数据库

And this is how I try to create and save the entity to the database.

using (var db = new Library())
{
    var reference = new TVSeriesReference
    {
        Id = 2,
        TheTVDBId = 1,
        IsWatched = true
     };

     db.TVSeriesReferences.Add(reference);

     try
     {
         db.SaveChanges();
     }
     catch (DbUpdateException e)
     {
         Debug.WriteLine("\n\n*** {0}\n\n", e.InnerException);
     }
 }

db.SaveChanges() 将抛出以下异常:

System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.TVSeriesReferences'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   --- End of inner exception stack trace ---
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()

我一直在撕裂我的头发几个小时,我不知道我做错了什么。看来表(或者也许整个数据库?)没有被创建。
有没有什么我应该设置或安装之前,这将工作?我已经安装了NuGet,并通过实体框架。

I have been tearing my hair out for hours and hours now and I can't figure out what I am doing wrong. It seems that the tables (or maybe the entire database?) is not being created.Is there something I should have set up or have installed before this will work? I have installed NuGet and through that the Entity Framework.

有没有人可以帮助我让这个工作?

Is there anyone who can help me get this to work?

更新:ConnectionStrings在 app.config

UPDATE: ConnectionStrings in app.config

<connectionStrings>
    <add name="Library"
         connectionString="Data Source=.\SQLEXPRESS"
         providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>


推荐答案

使用实体框架 / em>您仍然需要在 app.config 文件中设置适当的ConnectionString。例如,如果你想要一个本地数据库在文件中,你可以使用嵌入式SQL Server CE 4数据库引擎(当然,首先可以使用许多不同的数据库,包括SQL Server,SQL Server Express和MySQL):

While working with Entity Framework Code First you still need to set proper ConnectionString in your app.config file. For example if you want to have a local database in file, you can use embedded SQL Server CE 4 database engine (of course Code First can be used with many different databases including SQL Server, SQL Server Express and MySQL):

<connectionStrings>
    <add name="Library" connectionString="Data Source=|DataDirectory|CodeFirst.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

在运行时, DataDirectory 替换字符串被替换为应用程序当前执行环境的相应目录路径。没有 DataDirectory 替换字符串,您的应用程序将必须以编程方式根据当前执行环境确定数据库文件的位置,然后动态构建连接字符串中使用的路径。

At run time, the DataDirectory substitution string is replaced with the appropriate directory path for the application's current execution environment. Without the DataDirectory substitution string, your application would have to programmatically determine the location of the database file based on the current execution environment and then dynamically build the path used in the connection string.

代码优先还具有由初始化策略控制的自动重新创建的功能。默认的初始化策略是。如果您的ConnectionString指向不存在的数据库,则使用此策略代码首先将为您创建数据库,但如果数据库已存在代码第一将不会尝试创建它。

The Code First has also an auto-recreate functionality which is controlled by initialization strategy. The default initialization strategy is CreateDatabaseIfNotExists. With this strategy if your ConnectionString is pointing to database which doesn't exists Code First will create the database for you, but if the database already exists Code First will not try to create it.

可以使用 Database.SetInitializer()方法将初始化策略更改为以下之一:

The initialization strategy can be changed with Database.SetInitializer() method to one of the following:





  • DropCreateDatabaseAlways
  • DropCreateDatabaseIfModelChanges
  • MigrateDatabaseToLatestVersion

你需要记住的是,重建数据库将导致丢失存储在那里的所有数据。

You need to remember here, that recreating database will lead to losing all data that were stored there.

这篇关于代码首先与实体框架在保存时会引发DbUpdateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:29