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

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.

Related

Correct way/sequence to create DbContext

What is the correct way to generate a DbContext for my database. (I'm using database first.)
It looks like the EF 6.x DbContext Generator option generates empty files if I don't first create an ADO.NET Entity Data Model (EDMX file).
However, if I create the EDMX file first and then create the DbContext, I seem to get conflicting symbols with errors such as:
The call is ambiguous between the following methods or properties: 'BillsEntities.BillsEntities()' and 'BillsEntities.BillsEntities()'
And
d:\users\jonathan\documents\visual studio 2015\Projects\BillTracking\BillsDomain\BillsModel.Context.cs(23,33,23,48): error CS0111: Type 'Entities' already defines a member called 'OnModelCreating' with the same parameter types
And
d:\users\jonathan\documents\visual studio 2015\Projects\BillTracking\BillsDomain\BillsModel.Context.cs(28,36,28,41): error CS0102: The type 'Entities' already contains a definition for 'Bills'
And
d:\users\jonathan\documents\visual studio 2015\Projects\BillTracking\BillsDomain\BillsModel.Context.cs(29,39,29,47): error CS0102: The type 'Entities' already contains a definition for 'Payments'
And
d:\users\jonathan\documents\visual studio 2015\Projects\BillTracking\BillsDomain\BillsModel.Context.cs(30,39,30,48): error CS0102: The type 'Entities' already contains a definition for 'Utilities'
If that's not enough, I notice every time I generate a new EDMX file it seems to want to create a new connection string in my config file and doesn't seem to give me an option to use the existing one.
Can anyone point me to a resource that provides an example of performing these tasks in the correct way and the correct order? When I Google on this, mostly what I get is code-first articles that don't address this at all.
What is the correct way to generate a DbContext for my database. (I'm using database first.)
If you are using database first, you will need to and ADO.NET Entity Data Model.
It looks like the EF 6.x DbContext Generator option generates empty files if I don't first create an ADO.NET Entity Data Model (EDMX file).
You shouldn't be running any of these commands if you are using database first: Enable-Migrations, Add-Migration, Update-Database. Your first step is to create the EDMX file.
However, if I create the EDMX file first and then create the DbContext, I seem to get conflicting symbols with errors such as:
Once you create your EDMX file, your DbContext will also be created within the file. You can access this file by expanding your edmx file followed you by your .Context.tt and open up your .Context.cs class. Notice how the constructor for this class contains a :base("name=yourdbEntities"), which can be found in your web.config file.
If that's not enough, I notice every time I generate a new EDMX file it seems to want to create a new connection string in my config file and doesn't seem to give me an option to use the existing one.
Comment out your connection string and let it create a new one when you create your edmx file. If all is well, you can come back and delete it.
Here are a couple of resources you may find helpful:
http://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm
https://www.youtube.com/watch?v=o-cV_fSNMqw
I hope you find this answer helpful.

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:

Entity Framework - Use Web.Config Connection String

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.

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