I am learning with this so bear with me...I am trying to create the DB object to access the table.
AppDatabaseDataContext appDb = new AppDatabaseDataContext();
This gives me an error, so I create the constructor...
public AppDatabaseDataContext()
{
}
Now this tells me that System.Data.Linq.DataContext does not contain a constructor that takes 0 parameters. Why?
Thanks!
You need to specify a connection string. If you know it's always going to be the same (for example, localhost) you can just hard-code it in your parameterless constructor:
public AppDatabaseDataContext()
: this(#"Data Source=localhost;Initial Catalog=Foo;Integrated Security=True")
{
}
Notice how we chain the constructor to call the version that consumes a connection string. This way, you can instantiate the data context using the parameterless constructor, and it will use this default connection string.
Sometimes LINQ2SQL might become messy on properties window and the connection string might disapear.
If you can, restart all over, remove de Dbml and but DONĀ“T FORGET to delete from the web.config the connection string. Add a new Linq2SQL to your project and let the LINQ2SQL to create the connection string for U in the web.config.
It's strange. Every time I've used a "LINQ to SQL" DataContext in the past, it's always created a 0-argument constructor for me.
But today, I was finding that sometimes, in the Designer, it wouldn't let me select a particular (known) connection string in the Properties window... and when this happened, it refused to create this 0-argument constructor.
The solution was to manually add it myself.
My web.config contained a connection string called MikesConnectionString :
<configuration>
<connectionStrings>
<add name="MikesConnectionString" connectionString="Data Source=localhost;Initial Catalog=MikesDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
... so in my survey.designer.cs file, I added this:
public SurveyDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MikesConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
Job done.
But odd. Very odd.
Just Change your connection string just like
<connectionStrings>
<add name="DBLabConnectionString"
connectionString="Data Source=.\SQLExpress;Initial Catalog=DatabaseName;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Related
SHORT VERSION: Is it possible and how to define a variable in a web.config file that I can use within itself.
I am new to a company and also a beginner developer in C# MVC Web applications. I have been tasked to maintain and test a web application that has multiple connections strings in a single web.config file. These connection strings, however, have the same values in it like:
<connectionStrings>
<add name="DefaultConnection" connectionString="provider=System.Data.SqlClient;provider connection string="data source=SUPERCOMPUTER\SQLEXPRESS2012;initial catalog=HumanResourceDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=SUPERCOMPUTER\SQLEXPRESS2012;Initial Catalog=HumanResourceDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
As you can see, the difference with these two is just the Name of the connection. Since Im a beginner I don't exactly know why this application has to use 2 same connection strings with different names. I was told that one is being used by Database First entity framework and the other is being used by ASP.NET Identity Code First and I do not know right now what those are.
The problem: I am CONSTANTLY changing connection strings value to test with different machines/environment/database etc and the need to modify 2 connection strings is really slowing me down.
The question: Is it possible to use variables that I can just declare at the top of the web config file and use it in the connection strings so that I can just modify the variable values. Something like this:
var Server = SUPERCOMPUTER\SQLEXPRESS2012
var IntegratedSecurity = true
var database = HumanResourceDB
var user = databaseusername
var password = databasepassword
<connectionStrings>
<add name="DefaultConnection" connectionString="... data source=**Server**;initial catalog=**database**;integrated security=**IntegratedSecurity **;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=**Server**;Initial Catalog=**database**;Integrated Security=**IntegratedSecurity**" providerName="System.Data.SqlClient" />
</connectionStrings>
Additional Question: Is it really impossible to use one connection string if the mvc application relies on both Database First Entity Framework and Code First .NET Identity?
All EF project have a dbContext File..so you can use multiple EF projects(Code First, DB first) in just one solution.
Yes its clearly possible ...in code first your db context can get the name of each ConnectionString you want!.. like this:
public class AppContext : DbContext
{
public AppContext() : base("ConString Name")
{
}
}
so you can change the connection string name to another one..like DefaultConnectionString1 to DefaultConnectionString12 or 1000 ...
and you can have multiple db context to work on multiple databases to...
in Code first from database is like that to ...so in each part of project you can make instanse of which dbcontext you like. and do CRUD operation on that..
ask your advices about this:
I am trying to create db compact edition,
first time it was successfully with default dbName (ProjectName.dbContextName).
But i decided to define my own name, and added in app.config in connectionString sections my connection string. After db was not created.
From here MSDN Use code first with connection by convention i have done similar connection string:
<connectionStrings>
<add name="TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
(section name is equal to my dbcontext's name class.)
Just to be sure before dbContext will be created:
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
Db still is not created. What am i doing wrong? Thanks in advance.
VahidN, i tried to add call of base class constructor, but doesn't work. Don't understand. It should be very easy. And as were aforementionted in ref above, if name of connection string in config section and name dbContext class are equal - object finds its connection string without problems.
Well, debugger says that conString is defined correctly (equal to string in config section), but actually db is not created - i can't find it nor in appfolder nor in sql server folders.
You need to include the full namespace in the name of the connection-string. See here.
Something like this
<connectionStrings>
<add name="YourNameSpace.TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
Oh, sorry me for giving insufficient information, db was not created cause entities in dbContext was defined as List, not dbSet. inadvertency (
I want to create a single connectionString in my Web.config and then re-use it in the "provider connection string" attribute of all Modules declarations.
example :
Declare a connection string this way:
<add name="MyConnectionString" connectionString="Data Source=.;Initial
Catalog=MyDB;User ID=username;Password=pwd;" />
and then share this connection between modules:
<add name="Module1Context" connectionString="metadata=res//*/Module1.csdl| ... |
...;provider=System.Data.SqlClient;provider connection string=MyConnectionString"
providerName="System.Data.EntityClient" />
Is this possible?
It's not directly possible the way you have it described above.
The solution for this is almost certainly going to be FAR more work than just copying your connection strings, commenting or uncommenting entries as you go.
Be sure you are using Configuration Transformation files to manage this.
If you really must do this, then you will need to build the connection strings yourself, using the EntityConnectionStringBuilder class, pulling the provider connection string from your MyConnectionString value. Set the EntityConnection property in your context object when you instantiate it; see http://msdn.microsoft.com/en-us/library/bb896325.aspx for details.
You can manage your connection string in runtime using ConfigurationManager.ConnectionStrings
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx
An application of mine uses LINQ-to-SQL extensively, and it is now a requirement of the application to be able to switch which database it is looking at at runtime - so essentially I would like to be able to choose the connection string of my data context when I declare it.
Is there an easy way of doing this?
Just call :
DataContext context = new DataContext ("cxstring");
You could use an App.config to store your Connection Strings then use them to populate a drop down box or something. Then use the selected Connection string in the constructor of your LINQ2SQL data context.
App Config:
<configuration>
<connectionStrings>
<add key="ConString1" connectionString="ConnectionStringGoesHere"/>
<add key="ConString2" connectionString="ConnectionStringGoesHere"/>
</connectionStrings>
Use the ConfigurationManager class to access your connection strings.
string conString = ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
You can also enumerate over them or set them as datasource to populate a drop down box.
Then simply pass the selected string in as the first parameter in your LINQ2SQL datacontext constructor.
MyModelDataContext context = new MyModelDataContext(selectedConString);
If you mean by switching which database your application is looking at ,Test database and production database , simply you can make two connection string in your web.config file with the same key but has different connection string and comment one of them according to the desired database
<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=ProductionDB;" providerName="System.Data.SqlClient" />
<!--<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=TestDB;" providerName="System.Data.SqlClient" />-->
by comment and uncomment you can switch between the 2 databases in run time.
to choose the connection string of your context provide it with its constructor
DataContext Productioncontext = new DataContext ("MyConnectioString");
What does this error mean?
Format of the initialization string does not conform to specification starting at index 0.
and also getting this error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I'm trying to use my EF model context in another project in Visual Studio. Having real trouble just getting my EF application off the ground.
I instantiate the model context like so:
ctx = new VisitoriDataModel("VisitoriDataModel");
I have the connection string copied from the data layer project into all projects including the web.config and still no luck.
Also tried the following:
//model = new VisitoriDataModel(new EntityConnection("Name=VisitoriDataModel"));
//model = new VisitoriDataModel("Name=VisitoriDataModel");
//model = new VisitoriDataModel("VisitoriDataModel");
//model = new VisitoriDataModel();
ConnectionString is like so:
metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"
The connection string needs to go in the project that is being executed. If this is a website, that would be the web.config. Make sure it's correctly nested, and not inside another node like <system.web>, you should have:
<configuration>
...
<connectionStrings>
<add name="VisitoriDataModel" connectionString="metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
...
</configuration>
Also note that the "'s around the provider connection string inside the entity connection string need to be escaped as "