I'm having very few tables in my edmx (not more than 20)
I'm having big list of stored procedures (may be more than 1k) in my edmx.
EF version 5.0
Whenever I try to add/update model from DB it always throw this error, can any one help me out with this?
Unable to generate the model because of the following exception:
'System.Data.Entity.Core.EntityCommandExecutionException: An error
occurred while executing the command definition. See the inner
exception for details. ---> System.Data.SqlClient.SqlException: The
incoming request has too many parameters. The server supports a
maximum of 2100 parameters. Reduce the number of parameters and resend
the request. 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) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 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.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.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) --- End of inner exception
This kind of error is usually caused by to many object in a model (look like this is the case with all your procedures) and Entity Framework is not smart enough to make multiple database round trip.
You can find more information about this issue: https://social.msdn.microsoft.com/Forums/en-US/aafb63c4-61df-4d8d-9373-df78d6f7d686/entity-framework-vs-2012-designer-fails-calling-spexecutesql-with-too-many-parameters-when-updating?forum=adodotnetentityframework
Related
For SQL Server, I can get table descriptions from the metadata using:
SELECT
OBJECT_SCHEMA_NAME(t.object_id) as SchemaName,
t.name AS TableName,
ex.value AS Description
FROM
sys.tables AS t,
sys.extended_properties AS ex
WHERE
ex.major_id = t.object_id
AND ex.minor_id = 0
AND ex.name = 'MS_Description'
AND ex.value IS NOT NULL
But that throws an exception hitting an Azure SQL Database. How can I pull it from Azure SQL Database?
The exception I am getting is:
System.Data.SqlClient.SqlException occurred HResult=-2146232060
Message=Invalid object name 'sys.extended_properties'. Source=.Net
SqlClient Data Provider ErrorCode=-2146232060 Class=16
LineNumber=1 Number=208 Procedure=""
Server=tcp:odjidszumt.database.windows.net State=1 StackTrace:
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)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds)
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 net.windward.utils.ado.SqlServer.WrSqlServerDatabase.TableDesc(DbConnection
conn, String select) in
c:\vso\Jenova\team\refactoring\Engine\DotNetEngine\Kailua\net\windward\utils\ado\SqlServer\WrSqlServerDatabase.cs:line
465 InnerException:
I have no idea what version of Sql Database - we created a Sql Database on Azure and didn't do anything special so I'm guessing the latest.
Officially, according to this MSDN article, sys.extended_properties view is not supported in Azure SQL Database. The error message you provided says "Invalid object name 'sys.extended_properties'", which proved it's not supported.
However, the weird thing is that when I run the query from SSMS and SQL Server Object Explorer against an Azure SQL Database, it works. I then go back to the portal and notice that I created a V12 SQL Server, I then tried creating a V2 SQL Server and run the query against it, get the same result "Invalid object name 'sys.extended_properties'", see below snapshot:
So as per above test, I think 'sys.extended_properties' is only supported in Azure SQL Server V12 database. It seems MS official article might not be updated to the lastest. I'd suggest you check which version of Azure SQL Database you've created:
You can enable V12 when creating the SQL Server as below:
Found the Azure sys tables. I needed a solution to set columns requiring case sensitive comparison during a meta driven etl process. NOTE: might want to convert the d.[Value] field to something meta-model ingestible.
/*********************************
Returns Table Column Descriptions
*********************************/
Select
s.[name] AS SchemaName
,t.[name] AS TableName
,c.[name] AS ColumnName
,d.[value] AS Desription
From sys.schemas AS s
Inner Join sys.sysobjects AS t /* Tables*/
On t.[uid] = s.[schema_id]
Inner Join sys.syscolumns AS c
On c.id = t.id
Inner Join sys.extended_properties AS d /*Column Description*/
On d.major_id = t.id
And d.minor_id = c.colid
Where d.[name] = 'MS_Description'
I am facing a strange issue while reading a data using ADO.Net Entity framework.
I have two tables, "Surveys" and "PatientVists". "VisitId" is the primary key in "PatientVists" which is foreign key in "surveys" table.
I am using following query:
foreach (var survey in db.Surveys.Include(p => p.PatientVisit).Where(p => p.FacilityId == f.Id && p.IsCompleted == true && p.IsImaged == false).OrderBy(p => p.PatientVisit.MrnId).ThenBy(p => p.DateUpdated).ToList())
{
// reminign code
}
The above query seems pretty normal. But while executing the query I am getting thread abort exception. I can understand if I get timeout exception because of the large amount of the data. But I am not sure why I am getting thread abort exception. I am not explicitly spawning a thread. this code snippet is in the web service but I believe it's not related to that.
Following is the stack trace:
System.Threading.ThreadAbortException: Thread was being aborted.
at SNIReadSyncOverAsync(SNI_ConnWrapper* , SNI_Packet** , Int32 )
at SNINativeMethodWrapper.SNIReadSyncOverAsync(SafeHandle pConn, IntPtr& packet, Int32 timeout)
at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
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)
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.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
Is it reelected "ToList" operator or does "include" operator spawns a thread? Shall I replace it with Join? in general which is preferred method from performance perspective?
Please let me know if anyone has an insight into the particular exception
Thanks
I think this is the base thread that services the web application / service that is being timed out. If you spawn the process on its own thread, it should solve the problem.
You can also try the workaround posted here:
https://sharepoint.stackexchange.com/questions/9380/thread-was-being-aborted-with-sharepoint-2010
Add the code below to Web.Config:
< system.web >
< httpRuntime executionTimeout="36000" />
< / system.web >
It worked for me as a temporary solution until I change the code to run in its own thread!
I created a model-first diagram pointing to a couple of views on an existing DB. When I attempt to query said DB, EF attempts to create & update said DB (despite being told not to).
As with many existing DBs one wants to query, I have SELECT permissions, but not DB create permissions. I don't want EF mucking with creating ANY objects for this particular DB (MyDb)
There are a couple of strange things:
1. The model shouldn't need to update the DB (it matches the view)
2. Database.SetInitializer(null) //Set on MVC Application_Start
3. To troubleshoot, added. doesExist returns true, so EF should not attempt to create DB. Doubly so with the SetInitializer set.
using (var myDb = new MyDBContext1())
{
bool doesExist = myDb.Database.Exists(); //return true, the DB does exist!
}
I hope I am wrong, but this seems like a initializer bug in EF that is not honoring my preferences. Please prove me wrong :)
About my setup:
-Using Visual Studio 2013 Preview and EF6 Beta 1
-There is another "Code First" model and DBContext2 (for another DB) in the project. This DB I do own and can create/update the DB to match model changes (if I want to)
-DBContext2 had for some time Code Migrations turned on for it. I deleted all the config and migration table, thinking it may indirectly affect the other context (MyDBContext1), but it didn't help.
--Stack Trace--
//Why is DBMigration and AutoMigrate running here??
//Of course permissions are denied. I don't have SA access (nor need it) to this particular DB that
. I just want to run SELECT statements on.
System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=CREATE TABLE permission denied in database 'MyDb'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=262
Procedure=""
Server=MyDBServer
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.InternalDispatcher`1.Dispatch[TResult](Func`1 operation, Action`1 executing, Func`3 executed)
at System.Data.Entity.Infrastructure.DbCommandDispatcher.NonQuery(DbCommand command, DbInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass2f.<ExecuteStatements>b__2b()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 func)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action action)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass9.<Update>b__8()
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()
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext)
at System.Data.Entity.Database.Create(Boolean skipExistsCheck)
at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassc`1.<CreateInitializationAction>b__b()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
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)
.....
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
InnerException:
Do you have a static initializer in MyDBContext1?
static MyDBContext1()
{
Database.SetInitializer<MyDBContext1>(null);
}
The entity framework gives me generic messages in the exception without telling me the exact entity and the attribute which caused the error. How do I get more information about the error?
This happens in many cases such as
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
and
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
Exception details:
[SqlException (0x80131904): The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +404
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2660
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +118
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6431425
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6432994
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +538
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +256
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +19
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues) +270
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +391
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +11223976
System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +833
System.Data.Entity.Internal.InternalContext.SaveChanges() +218
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +291
Here's the code I have in my solution:
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
//raise a new exception inserting the current one as the InnerException
raise = new InvalidOperationException(message , raise);
}
}
throw raise;
}
You can use it as a basis to add into your solution ... it builds a nested set of exceptions with all the details from Entity Framework.
You need to write tests for repositories and in the base class for your tests:
try
{
DbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
throw;
}
This video shows me how to use Code First from an existing database.
http://msdn.microsoft.com/en-us/data/jj572367
So I use nuget to install EF Power Tools and I select my project, right click and choose;
Entity Framework -> Reverse Engineer Code First.
I select the database as outlined, but I get the following exception when I click OK;
System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.InvalidOperationException: This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection. ---> System.Data.SqlClient.SqlException: Login failed for user 'ictdev'.
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.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act)
at System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act)
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act)
at System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
--- End of inner exception stack trace ---
at System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
at System.Data.Entity.Design.EntityStoreSchemaGenerator.GetProviderSchemaMetadataWorkspace(DbProviderServices providerServices, DbConnection providerConnection)
at System.Data.Entity.Design.EntityStoreSchemaGenerator.CreateStoreSchemaConnection(String providerInvariantName, String connectionString)
at System.Data.Entity.Design.EntityStoreSchemaGenerator..ctor(String providerInvariantName, String connectionString, String namespaceName)
at Microsoft.DbContextPackage.Handlers.ReverseEngineerCodeFirstHandler.ReverseEngineerCodeFirst(Project project)
So the question is how do I fix this?
I found the solution on the comments of the webpage of the EF Power Tools product;
http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
In connection wizard, Advanced should be clicked and the value of Persist Security Info should be True.
If anyone can answer the original question and explain what is going on when you do this, I might tick them the answer!