Error getting data from second db context instantiated 'through' an interface - entity-framework

Currently working with codefirst v5 on .net 4.5
I have 1 'master' context which includes a locations table called 'Geonames' (snippet below)
public class CoreContext : DbContext
: base("Conn")
{
public DbSet<GeoName> GeoNames { get; set; }
}
The reference here is simply to be able to manage migrations on the table.
Site will have the ability to 'plug-in' different location providers and the geonames table is there to provide a local provider implementation.
The provider is set in the configuration of the website simply setting the classname and namespace of the actual implementation.
It uses an interface like this (simplified)
public interface ILocationProvider
{
IEnumerable<Location> LocationsByName(String Name);
}
The concrete implementation is instantiated as below (simplified)
public static ILocationProvider GetLocationProvider()
{
ILocationProvider Provider = null;
Provider = Activator.CreateInstance(Type.GetType("{selected namespace.classname}")) as ILocationProvider;
}
catch (Exception ex)
{
throw ex;
}
if (Provider == null)
{
throw new NullReferenceException("Could not create an instance of the location Provider");
}
return Provider;
}
The concrete implementation is as follows(simplified)
public class LocalLocationProvider : ILocationProvider
{
public IEnumerable<Location> LocationsByName(string Name)
{
List<Location> locations = new List<Location>();
using (var db = new LocalLocationContext())
{
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
locations.Add(
new Location { Id = item.Id, Name = item.Name, GeoLocation = item.GeoLocation }
);
}
}
return locations;
}
private class LocalLocationContext : DbContext
{
public LocalLocationContext()
: base("Conn")
{
Database.SetInitializer<LocalLocationContext>(null);
}
public DbSet<GeoName> GeoNames { get; set; }
}
}
The concrete implementation instantiates just fine and I call the method 'LocationsByName' .. but here the trouble starts. When the code line below executes
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
..
}
I get the following error.
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
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) +1379
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(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437
I have tried to instantiate 'LocalLocationContext' without using the 'Activator.CreateInstance()' method I can query the data just fine.
To me it seems obvious that it has got something to do with how I get my actual implemention of the location provider just can't spot what the error or issue is.
Thanks in advance.

Related

EF6 Syntax error when getting stored procedure results with parameter

I don't understand why I'm getting a syntax error when this line of code executes:
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
Here is the whole method:
public virtual ObjectResult<Kitti_getProductGroupDetail_Result> Kitti_getProductGroupDetail(Guid ProductGroupId)
{
var #params = new SqlParameter[]
{
new SqlParameter("ProductGroupId", ProductGroupId)
};
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
}
Here is the calling method:
public System.Collections.Generic.IEnumerable<ProductDetail> getProductDetailsFromSP(Guid ProductGroupId)
{
System.Collections.Generic.List<ProductDetail> productDetailList = new System.Collections.Generic.List<ProductDetail>();
using (var context = new EFDbContext())
{
var result = context.Kitti_getProductGroupDetail(ProductGroupId);
foreach (Kitti_getProductGroupDetail_Result res in result)
{
ProductDetail productDetail = new ProductDetail();
productDetail.ProductId = res.productid;
productDetail.SizeId = res.sizeid;
productDetail.SizeDescription = res.sizedescription;
productDetail.SizeRank = res.sizerank;
productDetail.ColorId = res.colorid;
productDetail.ColorDescription = res.colordescription;
productDetail.ColorRank = res.colorrank;
productDetail.QuantityRemainingInStock = res.quantityremaininginstock;
productDetail.ProductGroupId = res.productgroupid;
productDetail.ProductGroupName = "ProductGroupName is currently not in the stored procedure or in EF";
productDetail.Description = res.description;
productDetailList.Add(productDetail);
}
}
return productDetailList;
}
The result object:
public partial class Kitti_getProductGroupDetail_Result
{
public System.Guid productid { get; set; }
public System.Guid productgroupid { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public Nullable<System.Guid> colorid { get; set; }
public string colordescription { get; set; }
public int colorrank { get; set; }
public Nullable<System.Guid> sizeid { get; set; }
public string sizedescription { get; set; }
public int sizerank { get; set; }
public int quantityremaininginstock { get; set; }
public string productname { get; set; }
public string imagesrc { get; set; }
}
Finally here is my stored procedure:
ALTER PROCEDURE [dbo].[Kitti_getProductGroupDetail]
#ProductGroupId uniqueidentifier
-- Insert statements for procedure here
SELECT product.ProductId as 'productid', product.ProductGroupId as 'productgroupid', product.[Description] as 'description'
, product.Price as 'price', product.ColorId as 'colorid', color.ColorDescription as 'colordescription', color.ColorRank as 'colorrank',
product.SizeId as 'sizeid', size.SizeDescription as 'sizedescription', size.SizeRank as 'sizerank', product.QuantityRemainingInStock as 'quantityremaininginstock',
product.Name as 'productname', product.ProductImageSrc as 'imagesrc'
FROM dbo.Product product
INNER JOIN dbo.Color color
on color.ColorId = product.ColorId
INNER JOIN dbo.Size size
on size.SizeId = product.SizeId
INNER JOIN dbo.ProductGroup productgroup
on productgroup.ProductGroupId = product.ProductGroupId
WHERE product.ProductGroupId = #ProductGroupId
AND product.QuantityRemainingInStock > 0
ProductGroupId is definitely getting populated. What doesn't EF like about my code? I have a similar method that does not require a parameter to execute the stored procedure - it works fine
// this works just fine
public virtual ObjectResult<Kitti_getProductDetailsAndCategory_Result> Kitti_getProductDetailsAndCategory()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductDetailsAndCategory_Result>("Kitti_getProductDetailsAndCategory");
//ExecuteFunction changed to ExecuteStoreQuery
}
stack trace:
Incorrect syntax near 'Kitti_getProductGroupDetail'.
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 'Kitti_getProductGroupDetail'.
Source Error:
Line 40: };
Line 41:
Line 42: return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery("Kitti_getProductGroupDetail #ProductGroupId", #params);
Line 43: }
Line 44:
Source File: C:\Concrete\EFDbContext.cs Line: 42
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'Kitti_getProductGroupDetail'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2444082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5775560
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
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) +2127
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) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, Object[] parameters) +83
KittiCutieFashion.Domain.Concrete.EFDbContext.Kitti_getProductGroupDetail(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:42
KittiCutieFashion.Domain.Concrete.EFDbContext.getProductDetailsFromSP(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:82
KittiCutieFashion.Domain.Concrete.EFProductDetailRepository.get_ProductDetail() in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFProductDetailRepository.cs:33
KittiCutieFashion.WebUI.Controllers.ProductDetailController.ProductDetailView(String returnUrl) in C:\KittiCutieFashion\KittiCutieFashion.WebUI\Controllers\ProductDetailController.cs:43
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2558.0
The version of sql server I am using happens to be 2005 not sure if that has anything to do with it.

Problems with dynamic connection strings in Entity Framework 6 Code First

At the moment I am trying to use the code first approach of the entity framework 6 to create / connect to different databases on an SQL Express 2012 instance. The connection string to the database needs to be created in code and if the database does not exist it should be created on the SQL Express instance. Below is my class structure:
public class TestContext : DbContext
{
public TestContext()
{}
public TestContext(string connectionString)
: base(connectionString)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ChildItem>().HasRequired(s => s.Parent)
.WithMany(s => s.ChildItems);
base.OnModelCreating(modelBuilder);
}
public DbSet<ParentItem> Parents { get; set; }
public DbSet<ChildItem> Childs { get; set; }
}
[Table("Parents")]
public class ParentItem
{
public ParentItem()
{
Childs = new List<ChildItem>();
}
[Key]
public int ParentId {get; set;}
public string ParentName { get; set; }
public virtual List<ChildItem> Childs { get; set; }
}
[Table("Childs")]
public class ChildItem
{
[Key]
public int ChildId { get; set; }
public string Name { get; set; }
public virtual ParentItem Parent { get; set; }
}
When I now try to add Data for a new database or add data to an existing one I receive the following exception.
> System.Data.DataException was unhandled by user code
> HResult=-2146233087 Message=An exception occurred while initializing
> the database. See the InnerException for details.
> Source=EntityFramework StackTrace:
> 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.Internal.Linq.InternalSet`1.ActOnSet(Action action,
> EntityState newState, Object entity, String methodName)
> at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
> at System.Data.Entity.DbSet`1.Add(TEntity entity)
> at UnitTestProject.TestContextTest.InsertManyMeasurmentsDirectlyWithSql()
> in MSSQLTest.cs:line 123 InnerException:
> System.Data.Entity.Core.ProviderIncompatibleException
> HResult=-2146233087
> Message=An error occurred while getting provider information from the database. This can be caused by Entity Framework using an
> incorrect connection string. Check the inner exceptions for details
> and ensure that the connection string is correct.
> Source=EntityFramework
> StackTrace:
> at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
> providerServices, DbConnection connection)
> at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3
> k)
> at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey
> key, Func`2 valueFactory)
> at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection
> connection)
> at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection
> connection, DbProviderManifest& providerManifest)
> at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
> at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext
> context, XmlWriter writer)
> at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter
> w)
> at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1
> writeXml)
> at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext
> context)
> at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
> configuration, DbContext usersContext)
> at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
> configuration)
> at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext
> context)
> at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.<CreateInitializationAction>b__d()
> at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
> action)
> InnerException: System.Data.Entity.Core.ProviderIncompatibleException
> HResult=-2146233087
> Message=The provider did not return a ProviderManifestToken string.
> Source=EntityFramework
> StackTrace:
> at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
> connection)
> at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
> providerServices, DbConnection connection)
> InnerException: System.Data.SqlClient.SqlException
> HResult=-2146232060
> Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was
> not found or was not accessible. Verify that the instance name is
> correct and that SQL Server is configured to allow remote connections.
> (provider: SQL Network Interfaces, error: 26 - Error Locating
> Server/Instance Specified)
> Source=.Net SqlClient Data Provider
> ErrorCode=-2146232060
> Class=20
> LineNumber=0
> Number=-1
> Server=""
> State=0
> StackTrace:
> 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.Connect(ServerInfo serverInfo,
> SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
> Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
> integratedSecurity, Boolean withFailover)
> at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
> withFailover)
> at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
> SqlCredential credential, TimeoutTimer timeout)
> at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
> timeout, SqlConnectionString connectionOptions, SqlCredential
> credential, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance)
> at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
> identity, SqlConnectionString connectionOptions, SqlCredential
> credential, Object providerInfo, String newPassword, SecureString
> newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
> userConnectionOptions, SessionData reconnectSessionData)
> at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
> options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
> DbConnectionPool pool, DbConnection owningConnection,
> DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
> pool, DbConnection owningObject, DbConnectionOptions options,
> DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
> owningObject, DbConnectionOptions userOptions, DbConnectionInternal
> oldConnection)
> at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
> owningObject, DbConnectionOptions userOptions, DbConnectionInternal
> oldConnection)
> at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
> owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
> allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
> userOptions, DbConnectionInternal& connection)
> at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
> owningObject, TaskCompletionSource`1 retry, DbConnectionOptions
> userOptions, DbConnectionInternal& connection)
> at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
> owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions
> userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
> connection)
> at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
> at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1
> retry)
> at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
> retry)
> at System.Data.SqlClient.SqlConnection.Open()
> at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass2f.<UsingConnection>b__2d()
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1
> operation)
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action
> operation)
> at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection
> sqlConnection, Action`1 act)
> at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
> sqlConnection, Action`1 act)
> at System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection
> connection)
> at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
> connection)
> InnerException:
I have found out that the reason for this is that the TestContext.Parents.Add(..) calls the default constructor of my TestContext and that one does not call a base constructor. I have found a very dirty workaround for this which looks like the following.
public class TestContext : DbContext
{
private static string dbname = "TestDB";
public TestContext() : base(dbname)
{
}
public TestContext(string connectionString)
: base(connectionString)
{
dbname = connectionString;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
After this every things works fine but I do not like this solution. Especially when I will work with multiple threads supporting multiple database I will ran into a problem with the static variable.
If have already tried the solutions from the following sites but nothing had worked.
Entity Framework code first custom connection string and migrations
Changing connection string at runtime
So has anyone else some suggestions how this could be solved?
--- Edit: 24.03 ----
further investigations has shown that the described problem and the second call of the default constructor only occurs when the migration is enabled.
I have found a solution or better a workaround I can live with.
To solve the problem I use multiple database context to access the database. I will have on database context which reflects the complete database structure. For this database context the migration feature will be enabled. This database context will be used to create the database. With this limitation I can use the following code for the first database creation. But I need to be sure that only one thread at the time creates a new database.
public class TestContext : DbContext
{
private static string connection = "TestDb";
public TestContext() : this(connection)
{}
public TestContext (string newConnection) : base(connection)
{
connection = newConnection;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
…
The other database contexts are accessing only a part of the database system but set the database initializer to null. With this I can access multiple databases with dynamic strings and do not have the problems with the default constructor. I also can access the databases with different threads without worring about the static variable.
public class SecondTestContext : DbContext
{
public SecondTestContext (string dbName) : base(dbName)
{
Database.SetInitializer<SecondTestContext>(null);
}
…

Update-Database failed for a Private nuget package gallery

I'm trying to setup a local nuget gallery. While trying to create the DB manually (it doesn't support creating a database on the fly anymore) via Package Manager Console, I get the following error. Any ideas?
System.Data.SqlClient.SqlException (0x80131904): The operation failed because an index or statistics with name 'IX_CuratedFeed_PackageRegistration' already exists on table 'CuratedPackages'.
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable1 operations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
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()
ClientConnectionId:c4c6b7b3-c7e8-4d8b-802a-7433badcdcb8
The operation failed because an index or statistics with name 'IX_CuratedFeed_PackageRegistration' already exists on table 'CuratedPackages'.
This actually was a bug and has been resolved now. Check this - Update-Database failed because an index or statistics with name 'IX_CuratedFeed_PackageRegistration' already exists on table 'CuratedPackages'.

Error while calling saveChanges

I received the following error while adding new record
System.Data.Entity.Infrastructure.DbUpdateException was caught
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Navigation.RepositoryBase`2.Add(T entity) in c:\Users\afahmy\Documents\Visual Studio 2012\Projects\Navigation\REpositoryBase.cs:line 174
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
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.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Violation of PRIMARY KEY constraint 'PK_dbo.Priorities'. Cannot insert duplicate key in object 'dbo.Priorities'. The duplicate key value is (55c9b08f-1133-4246-9d0b-4f3e5192ffa5).
The statement has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=2627
Procedure=""
Server=dbsrv
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.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.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
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)
InnerException:
The code as follows
public virtual OperationResult Add(T entity)
{
OperationResult opStatus = new OperationResult { Result = QueryResult.Succeeded };
try
{
DataContext.Set<T>().Add(entity);
opStatus.Result = (DataContext.SaveChanges() > 0) ? QueryResult.Succeeded : QueryResult.Failed;
}
catch (Exception exp)
{
opStatus.ExceptionMessage = string.Format(" Error Adding {0}", exp.Message);
opStatus.Result = QueryResult.Failed;
}
return opStatus;
}
Apparently, the entity object has been fetched from the database before. If you add it to the context it will get EntityState.Added, which means that EF will try to insert it. And apparently you generate a primary key value client-side (i.e. not in the database), so EF tries to insert it with an existing PK value.
Since this is the DbContext API (apparent from the Set method, but always helpful to tag explicitly) you can use the IDbSetExtensions.AddOrUpdate method to let EF figure out whether the object needs to be inserted or updated.

SQL Server 2008 R2 "Login failed for user" using remote connection [duplicate]

I'm trying to execute an SQL Job using a CRM Workflow by making a custom activity. In my code, an online tutorial had me construct it like this (in c#):
[CrmWorkflowActivity("A test activity to run SQL Jobs")]
public sealed class ExecuteSQLJob : System.Activities.CodeActivity
{
#region Inputs
[Input("Job Name")]
[Default("BMS_ExtractTransformLoad")]
public InArgument<String> JobName { get; set; }
[Input("Server Connection")]
[Default("HBSSQL2008/MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
[Input("User Name")]
[Default("-----")]
public InArgument<String> UserName { get; set; }
[Input("Password")]
[Default("-----")]
public InArgument<String> Password { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
Server server = new Server(ServerName.Get(context)); //<--Is used here
try
{
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = UserName.Get(context);
server.ConnectionContext.Password = Password.Get(context);
server.ConnectionContext.Connect();
Job job = server.JobServer.Jobs[JobName.Get(context)];
job.Start();
}
finally
{
if (server.ConnectionContext.IsOpen)
{
server.ConnectionContext.Disconnect();
}
}
}
}
However, when I try to run this workflow, it throws an error saying it couldn't connect to the server. (Specifically, the error is thrown on the server.ConnectionContext.Connect() method call).
Is the problem the serverName String? If so, how can I find out the correct serverName to use?
Thanks for any help!
EDIT:
Here's some additional info...
This is how I got the server and instance name the first time:
And here's the error on the CRM Workflow:
Workflow suspended temporarily due to error: Unhandled Exception: Microsoft.SqlServer.Management.Common.ConnectionFailureException: Failed to connect to server HBSSQL2008.
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at ExecuteSQLJob.ExecuteSQLJob.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Inner Exception: System.Data.SqlClient.SqlException: Login failed for user 'rnkelch'.
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.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.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
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 Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
Sorry I didn't include this originally, thanks for your help so far
Although not entirely relevant to the question but nonetheless, a useful site to bookmark to aid in your getting the connection string right.
For SQL Server 2008, see this linky here, on the same site
Portion of the server string is this:
Server=myServerName\theInstanceName
You have used the forward slash in your declarative above
[Input("Server Connection")]
[Default("HBSSQL2008/MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
Change it to this:
[Input("Server Connection")]
[Default("HBSSQL2008\\MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
Might need to double-slash it to escape it..
Ok, I think I figured it out now.
Because there is only one instance of SQL running on our server, I don't actually need to use the ServerName\InstanceName format. Both hbssql2008 and HBSSQL2008 allow me to connect. In addition, the IP works as well.
Also, another issue I came across was the the user name and password I was using was from Windows Integrated Security, not the sql server's security. Therefore, I created a new account on the server with appropriate permissions and sql security info and it allowed me to connect.
Thank you all for your help!