EntityException was unhandled the underlying provider failed to open - c#

I am using VisualStudio2012 for the development. I have created a class library EMPDAL where I am using Employees table of NorthWnd database to connect with Entity Framework and I tested the connection while configuring the database. I have written below code to get employees details.
public class EmplooyeeData
{
public static List<Employee> GetEmployees( int EmployeeId)
{
using (DbEntities dbContext = new DbEntities())
{
return dbContext.Employees.Where(x => x.EmployeeID == EmployeeId).ToList();
}
}
}
I created a console application to use this EMPDAL so I had given the reference to my EMPDAL and using below code to retrieve employee details
static void Main(string[] args)
{
List<EmpDAL.Employee> emp = new List<EmpDAL.Employee>();
emp = EmpDAL.EmplooyeeData.GetEmployees(1);
}
But when client code calls GetEmployees(1) and debugger goes in to the EMPDAL.EmpDataGetEmployess method then in return statement it throws the exception ![Exception is shown below]
The underlying provider failed on Open.
AppConfig I have used same in my class library and client application.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>

You've made mention of at least two tiers to your application (class library and a console application). N-tier applications require you to have the connection string for your EF database to be declared in the web.config / app.config of all tiers of your application that Entity Framework is referenced in.
Ensure you have the connection string for your database listed in your console applications app.config as well as the class library's app.config.
As per the above comments from #Yuliam, it is worth ensuring you have the following in your connection strings:
Integrated security=True;
What this does is When it is set to True, .Net tries to open the connection with the current user event if you specify a user and password. Set the Integrated Security to False if you want to open the connection string as a specific user.

Related

Windows Service unable to connect to DB with EF6

I developed a Windows Service, using Entity Framework 6.
I run the service, and when it tries to connect to database, it throws the following exception:
No connection string named 'testEntities' could be found in the application config file.
so i decided to change this code in test.Context.cs
public testEntities()
: base("name=testEntities")
{
}
into this:
public testEntities()
: base("data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;MultipleActiveResultSets=True;App=EntityFramework")
{
}
in practice i changed the name of the entity to the connection string. But it throws the following exception:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception.
If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection.
To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
in the solution there are 2 projects (including wix for creating installation package). The same error is thrown if i set my project as "StartUp Project"..
Add the following sections to your app.config file.
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="testEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
/connectionStrings>
</configuration>
Where MyModel is the name of your database model.
Follow code
public testEntities()
: base("name=testEntities")
{
}
says that the connection string name in app.config is testEntities
Add connection string in app.config
<configuration>
...
<connectionStrings>
<add name="testEntities" connectionString="data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;" providerName="System.Data.EntityClient" />
...
I think it is better to add connection string to app.config
Add connectionstring in app.config
But If you want your solution . for get it to work
You should not set a default connection factory in app.config
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
So You must remove defaultConnectionFactory.
Have you checked the App.Config or Web.Config files? It is where the connection string is defined to connect the project with the database, make sure when you create the Code First to locate your server where the database is, this will edit the file and generate inside the connection string tag, which you can edit as you wish.

Refresh data source and connectionstring

Currently I using EF 5 and Oracle ManagedDataAccess for my application. I create a small tool to enable user to configure database connection while the application is running.They communicate using WCF SOAP. So mainly the changes will be on the application.
However, I am not able to refresh data source once EF is able to connect. Connection String is able to refresh, but not data source.
public Entities(): base("name=MyEntities")
{
}
public UnitOfWork()
{
_context = new Entities();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connection = config.ConnectionStrings.ConnectionStrings["Entities"].ConnectionString;
var connString = new EntityConnectionStringBuilder(connection);
context.Database.Connection.ConnectionString = connString.ProviderConnectionString;
}
My App.config will be look like
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/Mapping.Models.csdl|res://*/Mapping.Models.ssdl|res://*/Mapping.Models.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="data source=datasource1;password=123;persist security info=True;user id=user123"" providerName="System.Data.EntityClient" />
</connectionStrings>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="datasource1" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=W2K8R2o11G020)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PCMS))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
</configuration>
Once _context is established and able to connect to database, the datasource cannot be changed via my small tool. I still manage to change username and password with my small tool, but not data source (hostname, port, service name).
I tried to use OracleConnection.ClearAllPools(), but it is not working as well. Try to force new connection every time, not working too.
Is there any other way to make it happen?

External database MVC 5.2.2 membership

I have been fighting for days with the new Google OAuth, and I believe I got it to work (removed and reinstalled owin), but now when I hit my site, I get:
SQLExpress database file auto-creation error:
...The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory...
Indicating that it is trying to access a SQL Express db in the App_Data directory. I want it to connect to my existing external SQL Server
I have created a connection strings (two now).
I have tried to changing the connection string passed into the base of ApplicationDbContext to my connection string:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("myconnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
I tried both pointing to a straight connection string, and an entity string. The entity string originally errored out about tables not being included, but now it is giving me the same error.
I have tried changing the web.config to:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="[tried a connection string here as well]"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I have read hints like a line in FilterConfig.cs (that references a function that doesn't seem to exist in EF 5):
filters.Add(new InitializeMembershipAttribute());
I am just getting started with EF 5 coming from ASP.NET - The basic concepts are no issue, the framework is great and flexible, but Membership issues have been a beyond frustrating experience (and tiring that I've been at it this long)! I have created small sites in MVC without membership before...
Are there specific web.config entries that are missing, similar to those from the old school ASP.NET membership?
I am also using [Authorize(Roles = "a,b,etc")] - do I need to specify something specific for roles, or should the change to the identity class take care of it as well?
You need to add the connection string to your web.config. The base name set in the DbContext must match the name in the web.config and IS case sensitive.
Remote db looks like first line and local db looks like the second line.
Like this:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=0.0.0.0;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=someuser;Password=somepass" providerName="System.Data.SqlClient" />
<add name="mycontext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=mycontext-20150116012312; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|mycontext-20150116012312.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
... more content here ...
</configuration>
Hope this helps!

EntityFramework ignore login name in connectionString

Hi iam trying to configure my first application with EF but find no way to connect to DB
this is my context
public partial class FunzionamentoContext : DbContext
{
public FunzionamentoContext()
: base("FunzionamentoContext")
{}
static FunzionamentoContext()
{
Database.SetInitializer<FunzionamentoContext>(null);
}
public DbSet<Controllo> Controllo { get; set; }
}
this is connection string (present in app.config file of DAL project since i still don't have UI project):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FunzionamentoContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=xyzxyz; Initial Catalog=dbName;
Integrated Security=false;User ID=test;Password=test" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
this is a simply method i make to test connection (only for search if connection is done, next i will rewrite it in a more beautyful way :D)
[Test]
public void TestTrue()
{
FunzionamentoContext fctx = new FunzionamentoContext();
Controllo c = new Controllo();
.id = 1
fctx.Controllo.Add((Controllo)c);
fctx.SaveChanges();
}
When i try to connect i see this error:
FunzIA.UnitTest.DAL.TestFixture1.TestTrue:
System.Data.Entity.Core.EntityException : The underlying provider failed on Open.
----> System.Data.SqlClient.SqlException : Cannot open database "FunzionamentoContext" requested by the login. The login failed.
Login failed for user 'DOMAIN\U123456'.
where DOMAIN\U123456 is my windows account
Why EF use my windows account and not the one wrote in connection string?
I am assuming that you have your DAL in a separate project from the project you're actually running.
Your application will use the config file from the project you're trying to run, and not the one directly related to the DAL project.
By this, I mean, if you're only using the test project (assuming it's in a different project from the DAL) then you need the connection string in the app.config of your test project.

All artifacts loaded into the item collection must have the same version. Multiple versions were encountered

I'm getting this error when I try to access a view in my .edmx:
All artifacts loaded into an ItemCollection must have the same version. Multiple versions were encountered.
Here's the code that's genereating the error:
private IQueryable<daDialogNotes.viewDialogNotesAll> GetAuthorizedList()
{
List<int> authorizedClients = al.GetClientIds();
daDialogNotes.NTS2001Entities context = new daDialogNotes.NTS2001Entities();
IQueryable<daDialogNotes.viewDialogNotesAll> m;
m = context.viewDialogNotesAlls.Where(x => (authorizedClients.Contains(x.Client_Id))).AsQueryable();
// error in line above
return m;
}
Here's an image of my view:
App.config for the provider:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="NTS2001Entities" connectionString="metadata=res://*/DialogNotes.csdl|res://*/DialogNotes.ssdl|res://*/DialogNotes.msl;provider=System.Data.SqlClient;provider connection string="data source=NTS-UAT;initial catalog=NTS2001;persist security info=True;user id=*******;password=*********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
I'm running .net 4.5 on everything. The edmx is in another project file and I'm referencing the dll in my application. Googling around I see that people are getting this error when they're upgrading from .net 3.5 to 4.0, but this has always been running on 4.5.
Any ideas?

Categories

Resources