How can l use Entity Framework without App.config - entity-framework

I want to use Entity Framework without app.config file.
I want to define a string variable Connection String in my code and use that to connect to the database.
Please show me the way if it is possible.

You're not mentioning what approach you're using (database-first, model-first, code-first) - but basically, in the end, you need to define a string variable and assign it a valid EF connection string
string myConnectionString = "...(define a valid EF connection string here)......";
Example for database-first approach:
string myConnectionString = #"metadata=.\Model1.csdl|.\Model1.ssdl|.\Model1.msl;provider=System.Data.SqlClient;provider connection string="";data source=.;initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""";
and then use that to create your ObjectContext (database- and model-first) or DbContext (code-first)
using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
// do your EF magic here.....
}
But quite honestly - I think this is a really bad idea since this makes it impossible for you to move your application to another machine - no one else can install and run this, since the connection string is hard-coded into your C# code..... the whole point of having config files is so that you can change / adapt things like connection strings so that they are not tied to a single machine/location but can be adapted to the particular needs of a given user / customer....

Related

Automatic Migrations Set Connection String in code .NET MVC

How to configure Entity Framework to use different connection string when executing migrations and when working with the database.
The reason for that is quite simple, I do not want to have sa login for the website, but I want to be able to execute migrations.
After not finding anything on the web for how to do that, the Object Explorer helped.
The EF Migration Configuration class (where AutomaticMigrationsEnabled = true is set)
has also a property named TargetDatabase.
This can be set to whatever connection string you want like so:
TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(
ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString,
ConfigurationManager.ConnectionStrings["ConnString"].ProviderName);

Entity Framework ConnectionString Parsing Exception

I can't find how my connectionString syntax is wrong. Can anyone suggest a way to figure this out? I am having a difficulty using EF with my connection string. I am new to EF.
I am using Sybase Anywhere 12 database.
I'm using the Table-First ObjectContext with EDMX in a separate class library refenced by a web application.
I'm using a Ninject Module in my class library to bind my repositories.
I'm using a ODBC DataStore called "Test"
Other information EF 4.3.1.0, .NET 4, VS2010
My main web application web.config has the EF connection string copied to it as:
<connectionStrings>
<add name="Entities"connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl|res://*/MyEntities.msl;provider=iAnywhere.Data.SQLAnywhere;provider connection string="UserID=aUser;Password=aPassword;DataSourceName=Test"" providerName="iAnywhere.Data.SQLAnywhere"/>
</connectionStrings>
When I initialize my Entity/ObjectContext in my Repository (see using statement below) it returns an error: "The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid."
using (var context = new Entities())
{
return {Linq to Entity here}
}
I turned on CLR exceptions on the debugger and found the code throws the error in the .NET Framework here:
EntityConnection.cs
effectiveConnectionOptions = new DbConnectionOptions(setting.ConnectionString, EntityConnectionStringBuilder.Synonyms, false);
edmx designer generated:
/// <summary>
/// Initializes a new Entities object using the connection string found in the 'Entities' section of the application configuration file.
/// </summary>
public Entities() : base("name=Entities", "Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
I can see my connection string there, so it is having a difficult time parsing the connectionString. I have tried many different permutations of syntax and haven't found anything it accepts including:
Explicitly naming the assembly for entity files instead of a wildcard(e.g. metadata=res://MyDomain/MyEntities.csdl...)
Using Sybase friendly ODBC attributes such as UID instead of UserID, PWD instead of Password, and DBN instead of DataSourceName.
Thanks.
I got everything working and the only reason I can think of is that I deleted my ASP .NET 4.0 temp files. Also, I must add I changed my process from using an integration test to test this piece to using a unit test. I did not do unit tests first, because our build server does not have a database on it.
Once I was able to prove that it was working there, I decided to delete my temp files. After that, everything started working properly. So, some sort of cache issue was occurring in my application. I used the same connectionString that I mentioned above.
Actually, I used the domain name of the Metadata "metadata=res://MyDomain/MyEntitities.csdl" rather than */MyEntities.csdl. I don't plan on changing the domain any time soon. In fact, that is just what may have caused some of the issue, because I had changed the location, name, and namespace of MyEntities.Domain where the EF was.

DBcontext, dynamically specify connection string

I'm dealing with a C# application using EntityFramework and an object derived from DbContext.
I need to set programmatically the connection string when a new instance of MyDbContext object is created. In order to do so I use the following code:
public MyDbContext(string myString)
{
this.Database.Connection.ConnectionString = myString
}
myString = "Server=MYSERVER\\SQLEXPRESS; Database=MyDB; User ID=user; Password=pass;";
or
myString = "Data Source=|DataDirectory|\\AirecCalcDatabase.sdf";
The database providers are different for the two strings. SQLExpress for the first one, SQLCompact for the second one.
If I try to run this code with the first string, I get ArgumentException coming from the connection string. For example "Keyword not valid: server" but also "Keyword not valid: database". The connection string works when using the DbContext with no arguments, which is, reading the string from app.config
When you're wanting to use CE, you may need to change the DefaultConnectionFactory to point to SQL CE:
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
See this blog post for more information

Is it possible to retrieve connection string inside DDL generation template in VS2010?

I am playing around with creating a T4 template for the "DDL Generation Template option" (model first) process in Visual Studio 2010 RC. Is it possible to retrieve the connection string that is associated with that process? If I right click on the .edmx file and choose "Generate Database from Model..." I have the option of choosing a data connection. That connection string is saved to the app.config (assuming that the option is checked). So I am wondering if it is possible to retrieve that connection string inside the T4 template. I would like to generate different information from the template based on the connection string.
More generally, is it possible to get any context information in this situation? So far, the only thing I have successfully retrieved is the .NET data provider name.
Note - I have studied the ideas provided by Craig but am only getting the name of the IDE (devenv.exe), which quite possibly means I am just doing something wrong.
In case this helps anyone else, here is a snippet I created to read the Entity Framework connection string from inside T4. You pass it the model name (which is also the name of the connection string). It finds and parses just the connection bit I need. It also throws helpful errors when it does not succeed.
To use:
A. Paste this at the top of your template if you aren't already referencing these assemblies:
<## assembly name="EnvDTE" #>
<## assembly name="System.Configuration" #>
B. Paste this ugly (but compact) code at the end of your template:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
C. Use it like such:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
I posted my question on one of the MSDN forums and got a response from Lingzhi Sun who pointed me in the direction of a couple of links at skysanders.net. The second of these links has a very nice example of getting to the app/web.config file and, specifically the part I wanted, the connection strings. It doesn't give any information on the specific connection string for the scenario I described in the original question, but this gets me close enough.
Accessing app.config/web.config from T4 template
Accessing app.config/web.config from T4 template - Take 2
Well, the EF connection string will always have the same name as the model, right? The DB connection string will be embedded in the EF connection string. So I'd say you should be able to get it, at least indirectly, via the EF connection string.
Because you're not running in the assembly, have to specify the config file name.
So it would be something like:
var config = ConfigurationManager.OpenExeConfiguration(name);
var cs = config.ConnectoinStrings[modelName];
Note that name, here, is supposed to be an EXE name. But in the IDE, your config fine is going to be called App.config rather than MyApp.dll.config. So you may have to play around with this to get it to work -- try using "App" as the EXE name!
Worst case is open it as a file and then use the config manager.

Different Connection Strings with Entity Framework based on Context

I have a web forms application that uses entity framework, the application is deployed on a development box, my local machine and a production box. Each of these have different connection strings.
What is the best way of handling this.
I use TFS Build Server to deploy to development and take the result of that build zip it and copy it to production manually.
I also use Web Deployment Projects if that helps
What I was doing before was when the ORM started it would choose a connection string based on the name of the root folder. With Entity Framework I don't know how to do this without having to set it on every page.
We have something vaguely similar, I created a class to wrap the EntityContext object, which sets the connection string appropriately - you'd need something similar, based on how you set your connection string:
Public Class MyEntityModel
Private _dataContext As Entities
Public Sub New()
Dim entityBuilder As New EntityConnectionStringBuilder()
entityBuilder.ProviderConnectionString = MyApplicationConnectionString
entityBuilder.Metadata = "res://*/"
entityBuilder.Provider = "System.Data.SqlClient"
_dataContext = New Entities(entityBuilder.ConnectionString)
End Sub
Public Function DataContext() As Entities
Return _dataContext
End Function
End Class
FYI You can use config transformations now in VS 2010:
http://msdn.microsoft.com/en-us/vstudio/Video/ff801895