I am creating a Web Api in C#.Net. I have implemented Dependency Injection in it using Unity.Mvc5 and using Db First approach. Since then i'm facing some issues in connection strings. There is a default AccountController in it and I have created a TestController to test my Api's.
There are two connection strings in my Web.config file (one of them is commented but just to show here i have uncommented it).
<add name="DDEXEntities" connectionString="Data Source=DESKTOP-CSB6551;initial catalog=DDEX;integrated security=True" providerName="System.Data.SqlClient" />
<add name="DDEXEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-CSB6551;initial catalog=DDEX;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Now the problem is when I use the first string my test controller Api's don't work. The exception given is:
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
And when I use the second connection string, my Account controller doesn't work and produces exception:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
My UnityConfig.cs is as follows:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<DbContext, DDEXEntities>(new PerResolveLifetimeManager());
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<AccountController>(new InjectionConstructor());
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IGenreService, GenreService>(new TransientLifetimeManager());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
}
Can anyone let me know what I have done wrong. This is getting on my nerves now.
Thanks in advance.
Edit + Solution:
Based on Roman's answer, I named my first connection string as DefaultConnection and in ApplicationDbContext class constructor I gave this DefaultConnection. Now my AccountController uses this connection string and all other controllers use second connection string.
I hope it helps someone.
That's because AccountController uses your DbContext in CodeFirst mode. I think it's better to use separate DbContext: first one just for authentication and authorization(in CodeFirst mode) and second one for other stuff(in DatabaseFirst mode).
Also you can try to configure AccountController to use DbContext in DatabaseFirst mode.
I have an issue getting a DbContext to correctly pull my connection string from my local.settings.json
Context:
This is an Azure function project
The main problem code is in System.Data.Entity.Internal.AppConfig
Although I have a local.settings.json file this is not dotnet core. It's .net 4.6.1
Error message:
'The connection string 'ShipBob_DevEntities' in the application's configuration file does not contain the required providerName attribute."'
Json configuration:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"AzureWebJobsDashboard": ""
},
"ConnectionStrings": {
"ShipBob_DevEntities": {
"ConnectionString": "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=***;initial catalog=***;persist security info=True;User Id=***;Password=***;;multipleactiveresultsets=True;application name=EntityFramework'",
"providerName": "System.Data.EntityClient"
}
}
}
Configuration versions tested:
Moving the provider name into the actual ConnectionString token value : same error ocurrs
Setting the provider attribute inside the ConnectionString attribute to EntityClient: this did nothing
Making ShipBob_DevEntities a string value = to the value of ConnectionString : this throws new errors the likes of which are
keyword metadata is not supported
I tried using an ADO connection string which throws a code first exception which seems to occur when your connection string is incorrect in a database first approach.
I've taken the liberty to decompile EntityFramework.dll using dotPeek and have traced the problem down to System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig. Inside this method there is a call to LazyInternalConnection.FindConnectionInConfig which spits out a ConnectionStringSettings object that has it's ProviderName value set to null. Unfortunately I am unable to debug the AppConfig.cs class which it seems to use to generate this value so I am stuck.
So far I have consulted these two articles. One of which states to put the provider name as it's own token; however, this is not working.
https://github.com/Azure/azure-functions-cli/issues/193
https://github.com/Azure/azure-functions-cli/issues/46
Does anyone know the correct format to use in local.settings.json for an Entity Framework connection?
I went through several similar questions and answers here. Many of them are either misleading or assuming everybody is on the same level and understands how the azure functions are working. there is no answer for newbies like me. I would like to summarize here my solution step by step. I dont think that provided answer is the best option because it forces you to change the auto generated edmx files which can be overwritten by mistake or next update of your edmx from database. Also best option here is to use Connection strings instead of App settings in my opinion.
most important thing is that we understand local.settings.json file
IS NOT FOR AZURE. it is to run your app in the local as the name is
clearly saying. So solution is nothing to do with this file.
App.Config or Web.Config doesnt work for Azure function connection strings. If you have Database Layer Library you cant overwrite connection string using any of these as you would do in Asp.Net applications.
In order to work with, you need to define your connection string on the azure portal under the Application Settings in your Azure function. There is
Connection strings. there you should copy your connection string of your DBContext. if it is edmx, it will look like as below. There is Connection type, I use it SQlAzure but I tested with Custom(somebody claimed only works with custom) works with both.
metadata=res:///Models.myDB.csdl|res:///Models.myDB.ssdl|res://*/Models.myDB.msl;provider=System.Data.SqlClient;provider
connection string='data source=[yourdbURL];initial
catalog=myDB;persist security info=True;user
id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework
After you set this up, You need to read the url in your application and provide the DBContext. DbContext implements a constructor with connection string parameter. By default constructor is without any parameter but you can extend this. if you are using POCO class, you can amend DbContext class simply. If you use Database generated Edmx classes like me, you dont want to touch the auto generated edmx class instead of you want to create partial class in the same namespace and extend this class as below.
This is auto generated DbContext
namespace myApp.Data.Models
{
public partial class myDBEntities : DbContext
{
public myDBEntities()
: base("name=myDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
this is the new partial class, you create
namespace myApp.Data.Models
{
[DbConfigurationType(typeof(myDBContextConfig))]
partial class myDBEntities
{
public myDBEntities(string connectionString) : base(connectionString)
{
}
}
public class myDBContextConfig : DbConfiguration
{
public myDBContextConfig()
{
SetProviderServices("System.Data.EntityClient",
SqlProviderServices.Instance);
SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}
}
After all you can get the connection string from azure settings, in your Azure Function project with the code below and provide to your DbContext
myDBEntities is the name you gave in the azure portal for your connection string.
var connString = ConfigurationManager.ConnectionStrings["myDBEntities"].ConnectionString;
using (var dbContext = new myDBEntities(connString))
{
//TODO:
}
So the solution ended up being trivial. The ProviderName attribute specified in local.settings.json MUST be camel case.
From the original git hub discussions :
https://github.com/Azure/azure-functions-cli/issues/46
Shows the provider name as being pascal case
https://github.com/Azure/azure-functions-cli/issues/193
Shows the provider name being camel case in pseudo code
It was very easy to miss but your config section must be exactly as follows
"ConnectionStrings": {
"ShipBob_DevEntities": {
"ConnectionString": "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=***;initial catalog=***;persist security info=True;User Id=***;Password=***;;multipleactiveresultsets=True;application name=EntityFramework'",
"ProviderName": "System.Data.EntityClient"
}
}
These points are important:
Make sure your connection string has metadata information
If copying your string from an xml config, make sure you unescape apostrophes
Make sure the ProviderName attribute is camel case
Make sure the provider name is System.Data.EntityClient
Fix for missing providername in deployment
Note, this answer assumes you are trying to use the parameterless constructor of a DbContext. If you are creating new code you can easily follow the second upvoted answer
I figured out a way to circumvent the provider name issue while still retaining the use of the portal config and thus deployment slots. It involves setting the default connection string of db context using static properties
private static string _connectionString = "name=ShipBob_DevEntities";
static ShipBob_DevEntities()
{
if(!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("AzureFunction")))
{
var connectionString = System.Environment.GetEnvironmentVariable("EntityFrameworkConnectionString");
if (!string.IsNullOrEmpty(connectionString))
{
_connectionString = connectionString;
}
}
}
public ShipBob_DevEntities()
: base(_connectionString)
{
this.Configuration.LazyLoadingEnabled = false;
}
This involves the developer to create an app setting in the azure portal as a flag. In my case it is AzureFunction. This makes sure that our code is only run in an azure function and all other clients of this DbContext, whether they be web apps, windows apps, etc, can still continue behaving as expected. This also involves adding your connection string to the azure portal as an AppSetting and not an actual connection string. Please use the full connection string including them metadata information but without the provider name!
EDIT
You will need to edit your auto generated .tt file t4 template to make sure this code does not get overridden if you are using db first.
Here is a link on the T4 syntax: https://learn.microsoft.com/en-us/visualstudio/modeling/writing-a-t4-text-template
And here is an explanation on EF T4 templates: https://msdn.microsoft.com/en-us/library/jj613116(v=vs.113).aspx#1159a805-1bcf-4700-9e99-86d182f143fe
I encountered the similar issue before, I would use the following approach for achieving my purpose, you could refer to it:
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=brucchstorage;AccountKey=<AccountKey>",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=brucchstorage;AccountKey=<AccountKey>",
"sqldb-connectionstring": "Data Source=.\\sqlexpress;Initial Catalog=DefaultConnection;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"ConnectionStrings": {
"Bruce_SQLConnectionString": "Data Source=.\\sqlexpress;Initial Catalog=DefaultConnection;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
}
For retrieving the connection string:
var connString = ConfigurationManager.AppSettings["sqldb-connectionstring"];
//or var connString = ConfigurationManager.ConnectionStrings["Bruce_SQLConnectionString"].ConnectionString;
using (var dbContext = new BruceDbContext(connString))
{
//TODO:
}
Or you could init your no-argument constructor for your DbContext as follows:
public class BruceDbContext:DbContext
{
public BruceDbContext()
: base("Bruce_SQLConnectionString")
{
}
public BruceDbContext(string connectionString) : base(connectionString)
{
}
}
Then, you could create the instance for your DbContext as follows:
using (var dbContext = new BruceDbContext(connString))
{
//TODO:
}
Moreover, you could refer to Local settings file for Azure Functions.
Here are two approaches that work for me:
Approach 1
Add the connection string to the App Settings (respectively local.settings.json) in the following format:
metadata=res:///xxx.csdl|res:///xxx.ssdl|res://*/xxx.msl;provider=System.Data.SqlClient;provider connection string='data source=xxx.database.windows.net;initial catalog=xxx;user id=xxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework'`
Go to the class that extends DbContext ("TestEntities") and extend the constructor to take the connection string as argument
public partial class TestEntities: DbContext
{
public TestEntities(string connectionString)
: base(connectionString)
{
}
If you want then to interact with the database you need to retrieve the connection string from the app settings and then pass it over when initializing DbContext
string connectionString = Environment.GetEnvironmentVariable("connectionStringAppSettings");
using (var dbContext = new TestEntities(connectionString))
{
// Do Something
}
The problem with this approach is that every time you update the database you need to update the class "TestEntities" as it is overwritten
Approach 2
The goal here is to leave the class "TestEntities" as is to avoid the issue from Approach 1
Add the connection string to the App Settings (respectively local.settings.json) like in Approach 1
Leave TestEntities as is
public partial class TestEntities : DbContext
{
public TestEntities ()
: base("name=TestEntities")
{
}
As TestEntities is partial you can extend that class by creating another one that is also partial with the same name in the same namespace. The goal of this class is to provide the constructor that takes the connection string as argument
public partial class TestEntities
{
public TestEntities(string connectionString)
: base(connectionString)
{
}
}
Then you can go on like with Approach 1
I am using MVC 5 and sql server 2012.I have created DB with name TestDB its doest not contain any table.Now i am trying to use Identity which is default given in AccountController in MVC project. I have change in AccountController "Defaultconnection" to my TestDBEntities connection but i am getting error
System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context. How i can created Identity with exist Database.
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/DAL.TestModel1.csdl|res://*/DAL.TestModel1.ssdl|res://*/DAL.TestModel1.msl;provider=System.Data.SqlClient;provider connection string="data source=xxxxx;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("TestDBEntities", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
As per my understanding, the possible ways to solve your problem is:
1.Cross check that have you added the ApplicationDbContext to the UserStore constructor
Ex: https://stackoverflow.com/a/23894335/3397630
2.Also check that do you have any other connection string in the webconfig file. This may also cause the problem.
Finally if both above points doesn’t work, kindly follow the below article:
http://www.codeguru.com/csharp/.net/net_asp/mvc/securing-asp.net-mvc-applications-with-asp.net-identity.htm
It was really good, I personally used and created a identity tables for my projects without any issues.
In the articles, it was explained each , every points very well and easy understandable.
Hope the above information will be useful , kindly let me know your thoughts or feedbacks
Thanks
Karthik
I was working at an asp.net MVC project with the IdentityDbContext.
The code for the context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ApplicationDb")
{
}
}
And in my web.config a connectionstring named after the context:
<add name="ApplicationDb" connectionString="Data Source="..." providerName="System.Data.SqlClient" />
Strange thing is when I call the Update-Database command to create the database with Entity Framework, my database is created. So far so good.
But: the authorisation code from Owin is also creating a second upon running the application. This one is named DefaultConnection and is copy from the other one.
So my question: does Identity Framework always need a connection string named "DefaultConnection", even if you point the context to another connectionstring?
In the end I managed to solve this by adding the DefaultConnection connectionstring in web.config so I end up with two connectionstring:
ApplicationDb
DefaultConnection
Is this really the way to go? Because if that's the case it doesn't make much sense to put a custom connectionstring name in the base constructor?!
Btw, I also tried the context like so:
public ApplicationDbContext()
{
}
Which in theory should effectively do the same. But still DefaultConnection is created upon running the app. Doesn't make sense to me.
I have an application using Entity Framework 6.
I have project named Data where I have my DbContext.
public partial class MyDbContext: DbContext
{
static MyDbContext()
{
Database.SetInitializer<MyDbContext>(null);
}
public MyDbContext()
: base("Name=" + Utility.Constants.DbConnectionName)
{
Database.SetInitializer<MyDbContext>(null);
}
}
Where Utility.Constants.DbConnectionName = "TestConnection"
In my web.config of course I have:
<add name="TestConnection" connectionString="Data Source=MYSERVERIPADDRESS;Initial Catalog=unitdb;User ID=sa;Password=12345;Connect Timeout=600;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Then I also have a project that is a Windows Service.
Inside that project I have a reference to my Data project so I have a access to my Entity Framework entities. Also in my Windows service project I have an App.config with the same connection string (above) because If not then it won't know where to get the data.
Is there I way I can set inside my Windows service project a connection string dynamically? Because my windows service may connect to a different database (of course that database has the same structure so EF can get the info).