In a controller an object is built and saved into the database.
In the same controller action, I created another object of a different type and saved it (Class SecondType also includes an ID):
cDb.SecondType.Add(new SecondType { Designation = "test" });
cDb.SaveChanges();
That works. When looking at index (I created the classic create, delete,... views using the scaffolding options) or detail view I can see this object and I also can modify it. But, if I click on delete, it shows me the first view where I have to confirm the deletion and after pressing the submit button it returns a DbUpdateException without any further information at the SaveChanges command:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SecondType secondType = db.SecondTypes.Find(id);
db.SecondTypes.Remove(secondType);
db.SaveChanges();
return RedirectToAction("Index");
}
I don't know why this happens and I would be very thankful if you have any ideas to fix this.
This is what I could copy:
System.Data.Entity.Infrastructure.DbUpdateException ist aufgetreten.
HResult=-2146233087
Message=Fehler beim Aktualisieren der Einträge (= Error while updating the entries). Weitere Informationen finden Sie in der internen Ausnahme.
Source=EntityFramework
StackTrace:
bei System.Data.Entity.Internal.InternalContext.SaveChanges()
bei System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
bei System.Data.Entity.DbContext.SaveChanges()
bei Irgendwas.Controllers.SecondTypeController.DeleteConfirmed(Int32 id) in c:\Users\username\Documents\Visual Studio 2012\Projects\Irgendwas\Irgendwas\Irgendwas\Controllers\SecondTypeController.cs:Zeile 113.
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=Fehler beim Aktualisieren der Einträge. Weitere Informationen finden Sie in der internen Ausnahme.
Source=System.Data.Entity
StackTrace:
bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
bei System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
bei System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
bei System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Die DELETE-Anweisung steht in Konflikt mit der REFERENCE-Einschränkung 'FK_dbo.ThirdTypes_dbo.Second_SecondType_ID'. Der Konflikt trat in der 'Irgendwas.Models.SecondTypeContext'-Datenbank, Tabelle 'dbo.ThirdTypes', column 'SecondType_ID' auf.
Die Anweisung wurde beendet.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=547
Procedure=""
Server=.\SQLEXPRESS
State=0
StackTrace:
bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
bei System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
bei System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
bei System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
bei System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
bei System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
My german is a bit rough but I think you have entries in your dbo.ThirdTypes table that reference the entry you try to delete from the dbo.SecondTypes table.
Try to remove all dbo.ThirdTypes entries that reference the dbo.SecondTypes before you remove the secondType entry and call SaveChanges().
Like so:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SecondType secondType = db.SecondTypes.Find(id);
foreach (var thirdType in secondType.ThirdTypes)
{
db.ThirdTypes.Remove(thirdType);
}
db.SecondTypes.Remove(secondType);
db.SaveChanges();
return RedirectToAction("Index");
}
You can also enable Cascade Delete on the relation in your database.
Related
i am trying to recreate this sample
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/
I did everything according to the text, the program compiles fine, but then it fails creating the database
It seems like the db file
'C:\Users\WolfgangConsoleApp4.BlogContext.mdf' is missing a \ after Wolfgang.
But I do not know where to enter the path correctly.
On the laptop in my company I could rebuild and run the sample code without errors.
this is the complete exception text:
System.Data.SqlClient.SqlException
HResult=0x80131904
Nachricht = CREATE FILE encountered operating system error 5(Zugriff verweigert) while attempting to open or create the physical file 'C:\Users\WolfgangConsoleApp4.BlogContext.mdf'.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Quelle = .Net SqlClient Data Provider
Stapelüberwachung:
bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
bei System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c.<NonQuery>b__4_0(DbCommand t, DbCommandInterceptionContext`1 c)
bei System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
bei System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
bei System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass52_0.<CreateDatabaseFromScript>b__0(DbConnection conn)
bei System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass60_0.<UsingConnection>b__0()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass2_0.<Execute>b__0()
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
bei System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
bei System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
bei System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
bei System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
bei System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
bei System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
bei System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
bei System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
bei System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
bei System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
bei System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
bei System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
bei System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
bei System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
bei System.Data.Entity.Internal.InternalContext.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0()
bei System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
bei System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
bei System.Data.Entity.Internal.LazyInternalContext.<>c.<InitializeDatabase>b__58_0(InternalContext c)
bei System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
bei System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
bei System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
bei System.Data.Entity.Internal.InternalContext.Initialize()
bei System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
bei System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
bei System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
bei System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
bei System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
bei System.Data.Entity.DbSet`1.Add(TEntity entity)
bei ConsoleApp4.Program.Main(String[] args) in C:\Users\Wolfgang\source\repos\ConsoleApp4\ConsoleApp4\Program.cs: Zeile29
Maybe my VS Community Edition does not allow this?
Or maybe I have too many versions of sql server and localdb and so installed?
Greetings
Wolfgang
As #ErikEJ posted in a comment, I have to update my localdb install.
For this i used Cumulative Update 6 for SQL Server 2017.
After a restart of the pc it worked.
But code first migrations were not what i initially was searching for...
I think, I will have to post a new question...
I run in the following error message when I try to run the Seed method.
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred
while updating the entries. See the inner exception for details. --->
System.Data.Entity.Core.UpdateException: An error occurred while
updating the entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: The INSERT statement conflicted
with the FOREIGN KEY constraint "FK_dbo.Movies_dbo.Genres_GenreId".
The conflict occurred in database
"C:\USERS\PATH\SOURCE\REPOS\MVCMOVIE\MVCMOVIE\APP_DATA\MOVIES.MDF",
table "dbo.Genres", column 'Id'. The statement has been terminated.
This is my Configuration.cs file
namespace MvcMovie.Migrations
{
using MvcMovie.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<MvcMovie.Models.MovieDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "MvcMovie.Models.MovieDBContext";
}
protected override void Seed(MvcMovie.Models.MovieDBContext context)
{
context.Genres.AddOrUpdate(i => i.Title,
new Genre
{
Title = "Comedy"
},
new Genre
{
Title = "Romantic"
});
context.Ratings.AddOrUpdate(i => i.Title,
new Rating
{
Title = "General"
},
new MvcMovie.Models.Rating
{
Title = "Parentel guidence"
});
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
GenreId = 1,
RatingId = 1,
Price = 7.99M
},
new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
GenreId = 1,
RatingId = 1,
Price = 8.99M
},
}
);
}
}
}
Rating and Genres are set to be FK in the Movie table. Has anyone had this type of error before?
The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 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, Boolean
isInternal, Boolean forDescribeParameterEncryption) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry,
SqlDataReader ds, Boolean describeParameterEncryptionRequest) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) 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.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand
t, DbCommandInterceptionContext1 c) at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 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(Dictionary2
identifierValues, List1 generatedValues) at
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
--- End of inner exception stack trace --- at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator
ut) at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T
noChangesResult, Func2 updateFunction) at
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at
System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
options, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction) at
System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
options, Boolean executeInExistingTransaction) at
System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
options) at
System.Data.Entity.Internal.InternalContext.SaveChanges() --- End
of inner exception stack trace --- at
System.Data.Entity.Internal.InternalContext.SaveChanges() at
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at
System.Data.Entity.DbContext.SaveChanges() at
System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String
targetMigration) at
System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.b__d()
at
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.DbMigrator.Update(String
targetMigration) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
targetMigration) at
System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Incorrect syntax near 'ENTUserAccount'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'ENTUserAccount'.
Source Error:
Line 76: " WHERE " + fieldName + " = {0}" +
Line 77: " AND " + fieldNameId + " <> {1}";
Line 78: var result = db.ExecuteQuery(sql, new object[] { value, id });
Line 79: List list = result.ToList();
Line 80: return (list[0].DuplicateCount > 0);
Source File: c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs Line: 78
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'ENTUserAccount'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1753346
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5295154
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +1306
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +118
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +342
System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters) +83
System.Data.Linq.DataContext.ExecuteQuery(String query, Object[] parameters) +254
V2.PaidTimeOffDAL.Framework.ENTUserAccountData.IsDuplicate(HRPaidTimeOffDataContext db, String tableName, String fieldName, String fieldNameId, String value, Int32 id) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs:78
V2.PaidTimeOffDAL.Framework.ENTUserAccountData.IsDuplicateWindowsAccountName(HRPaidTimeOffDataContext db, Int32 userAccountId, String windowsAccountName) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffDAL\Framework\ENTUserAccountData.cs:69
V2.PaidTimeOffBLL.Framework.ENTUserAccountEO.Validate(HRPaidTimeOffDataContext db, ENTValidationErrors& validationErrors) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTUserAccountEO.cs:66
V2.PaidTimeOffBLL.Framework.ENTUserAccountEO.Save(HRPaidTimeOffDataContext db, ENTValidationErrors& validationErrors, Int32 userAccountId) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTUserAccountEO.cs:23
V2.PaidTimeOffBLL.Framework.ENTBaseEO.Save(ENTValidationErrors& validationErrors, Int32 userAccountId) in c:\Users\ClassicSofts\Documents\Visual Studio 2012\Projects\PaidTimeOffSolution\V2.PaidTimeOffBLL\Framework\ENTBaseEO.cs:49
Administration_User.Master_SaveButton_Click(Object sender, EventArgs e) in c:\Program Files\IIS\PaidTimeOffUI1\Administration\User.aspx.cs:27
PaidTimeOffEditPage.btnSave_Click(Object sender, EventArgs e) in c:\Program Files\IIS\PaidTimeOffUI1\PaidTimeOffEditPage.master.cs:27
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
I am having issues using the Entity Framework for simple CRUD operations. I do believe everything is configured correctly, but when I call SaveChanges after adding an entity to a DbSet, a DbUpdateException is thrown. I'm not quite sure which code to provide, so I'm going to include the exception detail and the logic involved.
Exception detail:
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:
Repository Add method
public bool Add(T entity)
{
_context.Add(entity);
_context.Entry(entity).State = EntityState.Added;
return _context.SaveChanges() > 0;
}
Controller action to add 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));
}
If you need more information to solve the issue, I will be able to give you individual access to my GitHub repo, but it is a private repo, so I cannot open it to everyone.
i got thrown into a small .NET migration project that is using the Entity Framework and MS SQL Server 2005. when persisting data that is not working with db schema (e.g. a string is too long), I am getting an exception System.Data.UpdateException that says "String or binary data would be truncated". But there is no information to which field it relates. does someone has a clue how to get this?
thx
here the stacktrace:
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.Objects.ObjectContext.SaveChanges()
at HAM.Inventory.Data.Repository.DocumentRepository.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Data\Repository\DocumentRepository.cs:line 177
at HAM.Inventory.Business.Managers.DocumentManager.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Business\Managers\DocumentManager.cs:line 75
at HAM.Inventory.MigrationClient.Common.Migration.SaveItem(ItemBase item) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 143
at HAM.Inventory.MigrationClient.Common.Migration.SaveAndClearItems(List`1 items) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 76
and the inner exception:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
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)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
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)
Look at the StateEntries property. It should have all the failing objects.