Where does EntityFramework get the connection string to my local database? - c#

I have created a web form that is a registration form using Identity. The form calls code behind that looks like this:
protected void CreateUser_Click(object sender, EventArgs e)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
}
else
{
StatusMessage.Text = result.Errors.FirstOrDefault();
}
}
And my web config file is this:
<?xml version="1.0" encoding="utf-8"?>
<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>
<system.web>
<authentication mode="Forms" />
<roleManager enabled="true" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I also have MS SQL Express installed on my machine. When i use the form the app creates a database in SQLExpress called DefaultConnection.
My question is how does entity/identity/.net know about my database at all, since I don't have the connection string written anywhere explicitly?
If this is somehow a feature of 'convention over configuration' then how can I explicitly direct entity to a different database?
Edit:
I have tried adding
<add name="MyConnection"
connectionString="[the connection string];TrustServerCertificate=False"
providerName="System.Data.SqlClient" />`
to the connection strings and updated my create user code:
...
var connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
var context = new System.Data.Entity.DbContext(connString);
var userStore = new UserStore<IdentityUser>(context);
var manager = new UserManager<IdentityUser>(userStore);
...
but this threw a InvalidOperationException with the following message:
Additional information: The entity type IdentityUser is not part of the model for the current context.
Last Edit:
Found out how to avoid the exception, changed this:
var context = new System.Data.Entity.DbContext(connString);
into this:
var context = new Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext(connString);

By convention a local database will be created on your local SQL Server instance.
See: Code First to a New Database - MSDN
By convention DbContext has created a database for you.
If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance
If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012)
The database is named after the fully qualified name of the derived context
You can over come it by specifying an explicit connection string in web.config like:
<configuration>
<connectionStrings>
<add name="MyDBContext"
connectionString="Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Here remember to change the name to the class that is extending DbContext in your code.
So for example if you are extending DbContext as:
public class MyDBContext : DbContext
then use MyDBContext as key for connection string in the configuration.
or off course you can pass the connection string in the constructor:
namespace MyCodeFirstProject
{
public class MyDBContext: DbContext
{
public MyDBContext() :
base("Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName") {}
}
}

Related

How to Pass Full Sqlite Connection String to DbContext

I am trying to pass the full connection string to DbContext constructor as an argument and I get this error:
Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
And this is what I have tried:
public DatabaseContext() :base(#"Data Source=|DataDirectory|ComponentDatabase.sqlite") {}
Problem can't be about anything else but connection string because I was able to connect my database using connection string from App.config like this:
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<!-- use AppDomain.SetData to set the DataDirectory -->
<add name="MapDbConnectionStr" connectionString="Data Source=|DataDirectory|ComponentDatabase.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.105.2" newVersion="1.0.105.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite.EF6" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.105.2" newVersion="1.0.105.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
DbContext
public DatabaseContext() :base("MapDbConnectionStr") {}
P.S. I know that App.config has a lot of unnecessary lines, yes.
As far as I am aware there isn't a Connection factory for the type of database you are trying to connect to.
You could write your own connection factory:
public class MySqlLiteConnectionFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string connectionString)
{
return new SQLiteConnection(connectionString);
}
}
now go and find the entry for defaulConnectionfactory in app.config and replace the line which specifies the type. At the moment thats going to read something like this:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
change it to something like this:
<defaultConnectionFactory type="MyNamespace.MySQLiteConnectionFactory, MyAssemblyHere" />
You should now be able to correctly use the Context ctor (string connectionString).
There is another was of doing this without relying on appsettings EF 6 and onwards supports code-based configuration.
So you can do something with configurations that looks a bit like this:
DbConfiguration.Loaded += (_, a) =>
{
a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s));
a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s));
};
Full details of this are documented here at microsoft:
Using the name from config file works because it can determine the provider type based on accompanying config provided. When using the connection string directly in the constructor it cannot determine that the connection string is for SQLite and assumes MSSQL so it is trying to use a SqlConnection. Hence the error message you encountered.
Take Note:
The connection to the database (including the name of the database)
can be specified in several ways. If the parameterless DbContext
constructor is called from a derived context, then the name of the
derived context is used to find a connection string in the app.config
or web.config file. If no connection string is found, then the name is
passed to the DefaultConnectionFactory registered on the Database
class. The connection factory then uses the context name as the
database name in a default connection string. (This default connection
string points to .\SQLEXPRESS on the local machine unless a different
DefaultConnectionFactory is registered.) Instead of using the derived
context name, the connection/database name can also be specified
explicitly by passing the name to one of the DbContext constructors
that takes a string. The name can also be passed in the form
"name=myname", in which case the name must be found in the config file
or an exception will be thrown. Note that the connection found in the
app.config or web.config file can be a normal database connection
string (not a special Entity Framework connection string) in which
case the DbContext will use Code First. However, if the connection
found in the config file is a special Entity Framework connection
string, then the DbContext will use Database/Model First and the model
specified in the connection string will be used. An existing or
explicitly created DbConnection can also be used instead of the
database/connection name.
Taken from the class remarks for DbContext
The last quoted sentence stands out...
An existing or explicitly created DbConnection can also be used
instead of the database/connection name.
You could consider using SQLiteConnection
public class DatabaseContext : DbContext {
public DatabaseContext()
:base(new SQLiteConnection(#"Data Source=|DataDirectory|ComponentDatabase.sqlite"), true) {
//...
}
//...
}
As i understood correctly it could be helpful, please use builder with db context options. I use SqlServer, hovewer there should be not a lot of changes.
var builder = new DbContextOptionsBuilder<MapDbContext>();
builder.UseSqlServer(ConfigurationManager.ConnectionStrings["MapDbConnectionStr"].ConnectionString), opt => opt.EnableRetryOnFailure());
var mycontext = new MapDbContext(builder.Options);
public MapDbContext(DbContextOptions<MapDbContext> options)
: base(options)
{ }
Hope it helps, Good luck.

C# Entity Framework: Keyword not supported: 'port'

Hello I have more than one project connecting to a certain DB that is CodeFirst Entity Framework.
All Projects are able to connect successfully except for one stubborn one.
The error I am getting is: Keyword not supported: 'port'
I have looked through countless stackoverflow questions, mysql forums, entity framework forums etc. including:
MappingException Edm.String not compatible with SqlServer.varbinary
Keyword not supported in MySQL's connection string
Keyword not supported: 'metadata' + MySQL
My connection string looks like:
server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123
My db.cs file looks like:
public partial class MyDB : DbContext
{
public MyDB ()
: base("server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123")
{
Logger.Trace("test123");
}
public virtual DbSet<MyItem> MyItems {
get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyItem>()
.Property(e => e.Content)
.IsUnicode(false);
}
}
When I remove the port:3306 from the connection string I get this:
System.Data.Entity.Core.MappingException: Schema specified is not valid. Errors:
(8,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.DateTime[Nullable=False,DefaultValue=,Precision=]' of member 'Time' in type 'something.Model.MyItem' is not compatible with 'SqlServer.timestamp[Nullable=False,DefaultValue=,MaxLength=8,FixedLength=True,StoreGeneratedPattern=Identity]' of member 'time' in type 'CodeFirstDatabaseSchema.MyItem'.
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths, Boolean throwOnError)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders)
at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToStorageMappingItemCollection(DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection, StoreItemCollection storeItemCollection)
at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToMetadataWorkspace(DbDatabaseMapping databaseMapping)
at System.Data.Entity.Internal.CodeFirstCachedMetadataWorkspace..ctor(DbDatabaseMapping databaseMapping)
at System.Data.Entity.Infrastructure.DbCompiledModel..ctor(DbModel model)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
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 MyFunction(Int32 userId, String id, String type, String contentJsonString) in
I am using MySql Connector and not Sql Server...
I am completely stumped by this as well as the rest of my team.
Edit:
Here is my Web.Config
<?xml version="1.0"?>
<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>
<appSettings file="config-sources\app-settings.config"/>
<system.web>
<compilation debug="true" targetFramework="4.5.2">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5.1"/>
</system.web>
<connectionStrings configSource="config-sources\ef-connection-strings.config"/>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="C5687FC88969C44D" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.8.3.0" newVersion="6.8.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="POST,HEAD,GET" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering>
<verbs>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
</security>
<defaultDocument>
<files>
<add value="webhook.ashx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
The argument of the used base DbContext constructor is called nameOrConnectionString. Hence it supports a name of a connection string from the configuration file, or like in your case an actual connection string.
The problem with the later is that it doesn't allow specifying the provider name as with the former coming from the configuration, in which case EF uses the one specified in the defaultConnectionFactory configuration element, which in your case is System.Data.Entity.Infrastructure.SqlConnectionFactory, in other words - Sql Server, hence the port not supported exception.
There are several ways to fix the issue.
(A) Change the defaultConnectionFactory configuration:
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"></defaultConnectionFactory>
(B) Use named configuration connection string and specify explicitly the provider:
<connectionStrings>
<add name="MyDB" providerName="MySql.Data.MySqlClient" connectionString="server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123" />
</connectionStrings>
and change the constructor to
public MyDB()
{
// ...
}
or if the name is different than your DbContext derived class name:
public MyDB() : base(connection_string_name)
{
// ...
}
(C) Use DbConfigurationTypeAttribute:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MyDB : DbContext
{
// ...
}
I had this problem whilst developing a Web Application on Core 2. I had to change the default database connection used from SqlServer to MySql in the Startup.cs file where the application is configured.
The error similar to the one listed above comes while working with ASP.net core and Database. The default database Provider with the ASP.net core is the SQL Server but, in case you are using a different provider for example, PostgreSQL and didn't correctly write or configure the DBContext code in the startup.cs
For example - Following code is written with an intent to connect to PostgresSQL then it will result in error ArgumentException: Keyword not supported: 'port'.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = #"Server=localhost;Port=5432;Database=NewDB;User Id=xxxxx;Password=cr#aaaa;";
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
// ...
}
And the reasons is user is trying to connect to PostgreSQL but did change the default Option UseSQLServer after configuring the PostgreSQL string.
To fix the issue change the option
options.UseSqlServer(connection)) -> options.UseNpgsql(connection))
I definitively solved the problem using the MySql Connector 8.0.x and following instructions on this link: https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken.
in details:
Install MySql.Data.EntityFramework. Do not install Install MySql.Data.Entity!
Configure web.config / app.config in this way:
2.1. Change the <entityFramework> tag to <entityFramework codeConfigurationType="MySql.Data.EntityFramework.MySqlEFConfiguration, MySql.Data.EntityFramework">
2.2. Add/change the provider. It has to be: <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />
2.3. Connection string now can be server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123
Open your DbContext's configuration class (if presente) and place the following code in it's constructor:
SetSqlGenerator("MySql.Data.MySqlClient" new MySql.Data.EntityFramework.MySqlMigrationSqlGenerator());
In my case, connection string with explicit port has to be delimited by ,.
E.g.: Data Source=123.45.123.45,1433;...
Sometimes it's the simplest thing. Mine was a copy-paste error when I missed the "Server=" at the beginning of the connection string.

Postgresql npgsql first connection takes too long

I am new to Postgresql. I am tring to use Postgresql with entity framework6, using npgsql.
I already have a database. I am using "Code First form database" option.
The problem is that the first time a query is executed, it takes me lots of time to execute it. I think that is when the connection is opened for the first time.
I created this simple example with the problem (TestJSONB is DbContext):
class Program
{
static void Main(string[] args)
{
TestQuery();
TestQuery();
}
private static void TestQuery()
{
using (DALJSONB.TestJSONB dataModel = new DALJSONB.TestJSONB())
{
var query1 =
dataModel.Database.SqlQuery<int>(
#"
SELECT 1;
");
query1.ToList();
var query2 =
dataModel.Database.SqlQuery<int>(
#"
SELECT 1;
");
query2.ToList();
}
}
}
The first execution times of TestQuery() are something like:
query1.ToList() - 2348ms
query2.ToList() - 2ms
The second execution times of TestQuery() are something like:
query1.ToList() - 19ms
query2.ToList() - 2ms
My app.config is:
<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="TestJSONB" connectionString="Host=x.x.x.x;Username=x;Password=x;Persist Security Info=True;Database=TestJSONB" providerName="Npgsql" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.1.0" newVersion="3.2.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Is it possible to decrease this time?
Thanks in advance.
This very likely has nothing to do with PostgreSQL or Npgsql, but rather with Entitt Framework itself starting up, building your model etc. try to connect to your database without EF (I.e. just creating an NpgsqlConnection and opening it) and you should see it runs pretty quickly.
It's common for EF applications to send sa sort of dummy warm-up query before actually servicing user calls, precisely to avoid this significant first-time delay.

SQL Server connection throw exception when using Entity Framework migration - add code snippet

I have a simple C# solution which has an entity class and a context class and also a console application which I use to test Entity Framework migration. But I always get this error:
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).
Here is the connection string in the app.config (I put it in both console's app.config and context class's app.config):
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
providerName="System.Data.SqlClient" />
I copied the connection string from "Connection string" property of the database from SQL Server ObjectExplorer so I suppose it is good.
Any suggestion why it always throws this exception?
I added entity class, context class and console class and hope this will have some clarification on my questions.
This is Entity class.
namespace Zza.Entities
{
public class Customer
{
public Guid Id { get; set; }
[MaxLength(50)]
public string FullName { get; set; }
}
}
This is Context class:
namespace Zza.Data
{
public class ZzaDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
}
This is console class:
namespace TestEFMigration
{
public class Program
{
static void Main(string[] args)
{
CreateDataBase();
}
private static void CreateDataBase()
{
var context = new ZzaDbContext();
context.Database.Initialize(false);
}
}
}
Console's app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
And app.config of context class:
<?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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Thanks.
I reduced connection strings.
As you are using localdb, it may have trouble with some of your parameters intended for full sql server (are you aware of it?)
Differences I found are:
connectionString="AttachDbFilename=|DataDirectory|\Zza.mdf;MultipleActiveResultSets=True;App=EntityFramework"
connectionString="Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
So, please try removing all options on second line and adding ones on top (AttachDbFilename can be a path to the mdf you want to use/create)
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;
AttachDbFilename=|DataDirectory|\Zza.mdf;MultipleActiveResultSets=True;App=EntityFramework;"
providerName="System.Data.SqlClient" />
EDIT: Ceck this
public class ZzaDbContext: DbContext
{
public ZzaDbContext()
: this("ZzaDbConnectionString")
{
}
// ...

Error in Early Bound Class in Dynamics CRM 2015

We are using CRM 2015 on-premise, we are trying to build customer portal, for that we generated Early Bound class
It is successfully generated and added to VS 2012. Now the problem is when i build the project in VS it goes fine and when i run the project it throws error in the Auto generated code
The code is below
public XrmServiceContext()
{
}
Below is my web.config code
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="Microsoft.Xrm.Client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
</configSections>
<connectionStrings>
<add name="Xrm" connectionString="ServiceUri=http://Contoso/XRMServices/2011/OrganizationData.svc/; Domain=MyDomain; Username=vsaravanakumar; Password=Password#5"/>
</connectionStrings>
<Microsoft.Xrm.Client>
<contexts>
<add name="Xrm" type="Xrm.XrmServiceContext, WebAppWalkthrough"/>
</contexts>
</Microsoft.Xrm.Client>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID">
<controls>
<add tagPrefix="crm" namespace="Microsoft.Xrm.Portal.Web.UI.WebControls" assembly="Microsoft.Xrm.Portal"/>
</controls>
</pages>
<authentication mode="None"/>
</system.web>
</configuration>
The exception im getting is "Unable to find connection string with name".
I got this error during debugging of my code
I followed each and every steps what MSDN website is mentioned in the website portal development, if i missed anything please help me to resolve this error
Below is my Web.config Code
You need to define the CRM connection string in your app.config/web.config files. If you don't specify a connection string the Client DLL defaults to using the Config file.
The CRMSvcUtil.exe is used to generate a set of classes that you can include in your project and then use to read and manipulate CRM data. But they don't "do" anything until you create a connection and then instantiate and use them. The simplified connection string method is covered here...
https://msdn.microsoft.com/en-us/library/gg695810.aspx
Essentially you put a conn string in web.config section like this...
<add connectionString="Url=http://crm.contoso.com/xrmContoso; Domain=CONTOSO; Username=jsmith; Password=passcode" name="Crm" />
Then somewhere before you use early or late bound objects, you do this...
//Use the Microsoft Dynamics CRM Online connection string from the web.config (or app.config) file named "CRM".
var connection = new CrmConnection("CRM");
var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);
With early bound you then can do a LINQ query against the generated code objects or {entity}Sets of the context like this...
var contacts = (from c in context.ContactSet
where c.LastName == "Smith"
select c);
This will return a collection of records matching your criteria that you could enumerate through with a foreach loop, or bind to a control, or send as a jSON array, or whatever you'd like.

Categories