实体框架7 Beta5 - DbUpdateException解析

时间:2015-07-18 04:30:09

标签: c# entity-framework

我在使用Entity Framework进行简单的CRUD操作时遇到了问题。我相信一切都配置正确,但是当我在向DbSet添加实体后调用SaveChanges时,会抛出DbUpdateException。我不太确定要提供哪些代码,所以我将包含异常细节和所涉及的逻辑。

例外细节:

Microsoft.Data.Entity.Update.DbUpdateException occurred
  HResult=-2146233088
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=EntityFramework.Relational
  StackTrace:
       at Microsoft.Data.Entity.Relational.Update.ReaderModificationCommandBatch.Execute(RelationalTransaction transaction, IRelationalTypeMapper typeMapper, DbContext context, ILogger logger)
       at Microsoft.Data.Entity.Relational.Update.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
       at Microsoft.Data.Entity.Relational.RelationalDataStore.SaveChanges(IReadOnlyList`1 entries)
       at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
       at Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
       at Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
       at Microsoft.Data.Entity.DbContext.SaveChanges()
       at Uniti.Data.Repository`1.Add(T entity) in D:\Alex\Projects\Uniti\src\Uniti.Data\Repository.cs:line 38
  InnerException: 
       Class=16
       ErrorCode=-2146232060
       HResult=-2146232060
       LineNumber=2
       Message=Invalid object name 'UnitiPost'.
       Number=208
       Procedure=""
       Server=(localdb)\MSSQLLocalDB
       Source=.Net SqlClient Data Provider
       State=1
       StackTrace:
            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, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
            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()
            at Microsoft.Data.Entity.Relational.Update.ReaderModificationCommandBatch.Execute(RelationalTransaction transaction, IRelationalTypeMapper typeMapper, DbContext context, ILogger logger)
       InnerException: 

存储库添加方法

public bool Add(T entity)
    {
        _context.Add(entity);

        _context.Entry(entity).State = EntityState.Added;
        return _context.SaveChanges() > 0;
    }

添加UnitiPost的控制器操作

[HttpPost]
    [Route("Add")]
    [Authorize("Bearer")]
    public async Task<IActionResult> Add([FromBody] UnitiPostAddDto postAddModel)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByIdAsync(User.GetUserId());

            var post = new UnitiPost
            {
                Creator = user,
                CreateDateTime = DateTime.UtcNow,
                UpdateDateTime = DateTime.UtcNow,
                Content = postAddModel.Content
            };

            var add = Repository.Add(post);
            if (!add)
            {
                return Json(false);
            }

            return Json(true);
        }

        return Json(new FailureResult(null, ModelState));
    }

如果您需要更多信息来解决问题,我将能够让您个人访问我的GitHub仓库,但它是私人仓库,因此我无法向所有人开放。

0 个答案:

没有答案