Entity Framework - Use Web.Config Connection String - c#

Setup - ASP.Net Web Application referencing a separate project which contains the dbml(soon to be edmx) and business logic classes.
I've been using Linq-To-SQL for a few years now and have been using the same setup as is described here for connection string passing from the web.config.
Can the provider connection string of Entity Framework be substituted with a DB connection string already defined in web.config?
So we have added another object context partial class and passed in the connection string using the constructors.
But this has the irritation of forcing me to manually delete the two constructors from the top of the dbml designer class every time it is rebuilt. We are moving to entity framework soon.
Is the same method recommended for EF? And do you still have to manually remove the two constructors on each rebuild?

http://www.connectionstrings.com/
You can find any specific connectionstring you want there. This is dependent on which type of database you are using, I can't explain further because I don't know which one you have.

Related

Entity Framework database connection string and class library without startup project?

I am having a bit of trouble with Entity Framework and class libraries. We already have databases, so I chose to use database first approach to get type safety.
The resulting dll file is supposed to be consumed by another application, which allows creation of custom "agents" in the form of a dll file.
For testing I use PowerShell to instantiate the classes and call their methods.
Now, you might already see the problem. There is no such thing as a startup project. All I have are class libraries to be consumed.
At runtime, EF cannot find app.config file, nor use the connection string therein. Which of course produces following error:
Exception calling "GetPersonStaff" with "0" argument(s): "No connection string named 'StaffEntities' could be found in the application config file."
Then I tried to explicitly give the class inheriting DbContext a connection string. But that led to following error:
Exception calling "GetPersonStaff" with "0" argument(s): "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 st
ring 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 t
hat 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.micros
oft.com/fwlink/?LinkId=394715"
I am kinda stumped now. I tried to google for a solution, but they all either tell me to change startup project, copy app.config/web.config to startup project, or use explicit connection string. None of which are usable in my use case, I believe.
How should I tackle this problem? Thank you in advance.
Well, I figured this out. The correct approach is "Code First from Database", which allows explicit connection string to be used.

Entity Framework on .mdf file

I am working on some project at the moment and I have to use local database. So, I created a new service-based database (no tables atm). Then I wanted to add Entity Framework support.
Because I never used Entity Framework before, I was referring to that link: http://msdn.microsoft.com/en-us/data/jj200620.aspx.
Everything is OK, but here it gets complicated. I created my DataContext class with DbSet inside it. But, when I run my unit test, table is created on Localdb (not inside my .mdf file).
What to do?
I am pretty sure, that I did choose which database to use correctly (actually did that 3 times already), but still, data tables are created on LocalDb. What I am doing wrong here?
I am complete beginner with that (been only using doctrine ORM). Otherwise I can insert data and all, it is just on the wrong database.
When your doing code first development in EF, you can force EF to only ever consider one connection string name.
One of the constructors (of which there are quite a few overloads) on the EF Data Context parent classes, takes a simple string.
This string is given to be the name of a connection string in the App or Web config to use.
You make the call something like this:
using System.Data.Entity;
namespace MSSQL_EFCF.Classes
{
public class DataAccess : DbContext
{
public DataAccess() : base("myConnectionString")
{}
public DbSet<MyTableObject> MyObjects { get; set; }
}
}
You can still put any code you need for your own start-up (Such as DB Initializer calls) inside your constructor, and all that will get called once the base call completes.
The advantage of doing things this way forces entity framework to always use the named connection string and never anything else.
The reason this catches many developers out, and why it runs off an uses localdb is deceptively simple.
The Entity Framework DbContext by default will use the name of the data context derived class as a database name, and if it can't find a suitable connection string in any config file by that name, makes the assumption that your working in development mode without a full backing data store.
In my example above, EF would examine App and/or Web.config for a connection string called "myConnectionString"
Once it makes this development decision, it knows that localdb will be present as this gets installed with the latest builds of visual studio, and so it will automatically seek out a connection and populate it with a db that follows the name of the context in which it's used.
I've previously written a blog post on the subject, which you can find here :
http://www.codeguru.com/columns/dotnet/entity-framework-code-first-simplicity.htm
NOTE: The above applies to any database that you connect with using EF, it's the connection string that decides what/where the actual data store is.

Entity Framework 5 Lost its Connection String

I have used EF5 for my project and I encrypted my connection string in project's web.config file.
And I replaced the constructor of Entities like this:
public PEntities()
// : base("name=PaypalEntities")
: base(Cryptography.DecryptConnectionString())
{
}
But when I want to update my database model with EF wizard, it asks to me for a new connection string and credentials and replaces my connection string in my config file with this. So my project doesn't run properly.
How can I solve this problem?
I'd strongly encourage you to have the Entity framework model in a separate project. If you do that, the project can have its own connection string that points to your reference database (the one you use for making changes as and when necessary). Thus, the running assembly, whether it be a web project or anything else, will just refer to the model project and can have its own connection string.
Yes...
The Solution is, Create a Partial class with same namespace and write the method into it.
Now whenever you update database or edmx file you will find it's default constructor. just delete it.
refer this
http://forums.asp.net/post/4722699.aspx
Try to uncheck the "Save entity connection settings" checkbox:

Code First vs. Database First

I created an Entity Framework model based on an existing database, then generated the POCO entities from the model. The connection string in my web.config isn't Entity Framework, it's just the standard connection string (it's missing the CSDL, SSDL, MSL references).
I can compile my application, but when I run I get this error:
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application. To use these classes, that were generated from
Database First or Model First, with Code First add any additional
configuration using attributes or the DbModelBuilder API and then
remove the code that throws this exception
My question is, where in my code does it realize the POCOs came from auto generation, and how can I get it to behave like Code First? I don't want to reference the CSDL etc in my connection string.
If the connection string has the metadata, EF thinks it is Model First or Database First. If it is a plain connection string, EF thinks it is Code First. However, if you want to start out doing model first but make EF think you are really doing code first (which is what you are doing), make sure you are using the DbContext code generator, not the default one. Code first POCOs are really that--"plain old c# objects"-- no special database aware or change tracking stuff in them at all. To use the DbContext code generator, right click on your model diagram and choose "Add new code generation item..." then select the ADO.NET DbContext Generator. Also, depending on how you named your primary and foreign keys and/or whether they are more complicated than just simple int IDs, you will probably need to fill in some code to map the relationships between your objects in the "OnModelCreating" method in your context. Delete the line throw new UnintendedCodeFirstException(); and replace it with your mapping code. Otherwise EF may not be able to figure out all the relationships (remember there's no metadata for it to rely on).
Hope this helps.
You need the following in your config file:
<connectionStrings>
<add name="<The name of your class>"
connectionString="metadata=res://*/<test>.csdl|res://*/<test>.ssdl|res://*/<test>.msl;provider=System.Data.SqlClient;provider connection string="data source=<your source>;initial catalog=<your db>;persist security info=True;user id=<your user id>;password=<your password>;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
I'm using Database first and resolved this by copying the EDMX generated connection string to the app.config of my startup application. One already existed but apparently they were different

Moving Entity Framework model into class library from web project

I am using Entity Framework and recently came to realize the benefits of having your EF model in another project within the same solution so that I can build multiple UIs from it.
I moved it over to a new class library project and updated all the references to the entities in the web project to use the new dll generated by the project. Everything has gone smoothly, except for one small snag. When I moved EF over to the new project, somehow it was still reading its connection string from the web.config in the web project (don't ask me how because I have no clue).
I used "Update Model from Database" in the EF designer and it did not find a connection string (as I expected after moving it over to the new project) so I used the wizard to generate a new connection string, which it did just fine. The new connection string now resides in App.config within the class library project. The connection string in the properties window is correct now, and the designer is reading it from the App.Config. I went ahead and deleted the connection string from Web.Config in the web project.
Now when running the application I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
If I paste the connection string back into the Web.Config it all works just fine. I do not want to create a new EF model from scratch because it is a fairly complicated model and I did a lot of restructuring after pulling in from the DB. I have poured over the generated CS file as well as the XML in the edmx file and cannot find anything useful. Any help is much appreciated. Obviously for now, until I figure this out, I'm just leaving the connection string in web.config since, for whatever reason, that seems to work.
This is by design; while the config file in the class library is what the designer will use, the configuration file of the actual application is what will get used at runtime. Whether that's Web.config for an ASP.NET project or App.config for a Winforms or WPF project, it's the application configuration file (or something higher up, like Machine.config) that will be used; the file in the class library is not part of the application.
If you're trying to provide an EF model that will work without having to specify the connection string in the application or web configuration file, then you'll have to store the connection string some other way (you could always hard-code it) and pass it into the appropriate overload of your context's constructor.
My solution is generally to provide a static parameterless function on the context itself that calls this overload with the appropriate connection string.

Categories

Resources