Multiple connection strings and Entity Framework - c#

I've been dabbling a bit recently with Entity Framework 5.0. The application that I'm writing currently uses a database on a development/testing server. Once the application is complete, though, it should be able to connect to multiple instances of the database on different servers. Basically, the same database will be on several different serves. They have the exact same layout, just different information contained within.
The user should be able to select which server they will access from a dropdown on the form. Using their choice, the program will connect to the correct database server.
So, I'm wondering what caveats I should keep in mind while attempting this? Is it feasible/doable to let the program choose a different database/server based on user input? Will I have any special considerations because of using EF 5.0?

So long as you can guarantee the database layout is identical - and having non-sync'd data is intended, you should have no problems with this.
I believe you will have to add a new constructor for your context using a partial class that will accept the connection string.
public partial class MyContext
{
public MyContext(string connectionstring) : base(connectionstring){}
}
And that should do it.
Make sure to use an Entity Framework friendly connection string. See http://msdn.microsoft.com/en-us/library/vstudio/cc716756(v=vs.100).aspx
Using different connection strings is frequently done to target different development / production databases. I've never run across your usage - but it should function just the same.

Related

Combine Class with Database first model

I've got an older ASP project that is being re-written into a responsive MVC4 w/bootstrap web application. The original version used direct SQL queries to interact with the application backend SQL database, and a custom class called EmployeeUserInfo that directly queries the ERP system for current employee information(current tasks, hours worked, etc). That connection is strictly read-only.
Using Entity Framework, it was extremely easy to create the models for the various writable databases that make up the application, but how can I add the original EmployeeUserInfo class to this EDMX model? I'd prefer not to rewrite the class because it does a lot of querying and analyzing to build the EmployeeUserInfo object. Is it possible to combine another class with an EF database-first generated model?
I'm stuck now because I can use the EmployeeUserInfo as the model for a view, but then I cannot access the EF generated model to read/write to the application database. I feel like I'm overlooking something here and making this more difficult than it needs to be.

Using LINQ to SQL for two different databases

I have a Router that saves changes from incoming messages to a database that is used by our CRM software. The Router uses LINQ to SQL for communication. We just released a completely revisioned version of the software that was built from the ground up, and runs on a different database.
Rather than maintaining two Routers with almost identical code, we want to change the code to work on either database, and change the context dynamically. This requires having a DataContext for each of the two formats.
My question is, can I have a DataContext for a database that doesn't exist on the system as long as the context is never used? I plan on refactoring all database communication to a single dll, and use two different classes that implement the same interface to access the two different databases. I will then only call methods in the correct class, but the dll would hold both DataContexts.
Thanks.

Using Entity FrameWork with multiple MS SQLSERVER Databases

I have searched back and forth but seemingly could not get a hold of what I need. I am sorry if this has been answered of late. A redirection to the discussion will do me good.
This is the scenario. I have been instructed to move from Microsoft Visual Foxpro (MS is withdrawing support come 2015) to .Net C# by my boss. For the sake of good foundation and adoption of best practices, I have decided to first learn, piece pertinent information together, then start coding. This is the second year.
We are a bureau company that offer payroll processing outsource services to over 50 clients. Each client currently has their own database. The databases have tables with completely identical structures.
I am a newbie. Totally new to .net world.
I had started off with raw SQL using datatables, datareaders but in my research I got some discussions discouraging this. Many were of the view that Entity Framework should serve the purpose. But one is allowed to mix approaches especially when complex queries are involved.
Can someone point me to some 'good read' where I can implement Entity Framework with over 50 indentical databases. Each database is totally independent and has nothing to dowith any other. When the user logs in, they select which client they need to process payroll for, then EF points to that database.
EF needs 2 different pieces of information to work with data from a database:
1) The database schema: This is included as compiled code in your application and cannot normally be changed at runtime.
2) The connection string: This is provided at runtime, normally from a config file.
In your case, all the databases have the same schema, so you can just model one database and it will work for all the others.
The piece you want to change is the connection string. This tells EF how to find the database and can be provided at runtime.
There is an overload of the DbContext constructor which takes a connection string as a parameter: MSDN: DbContext Constructor (String)
And there are even classes in the framework that help create connection strings for you:
MSDN: EntityConnectionStringBuilder Class
MSDN: Connection String Builders
It is very simple
I had,
//WMSEntities is conection string name in web.config
//also the name of Entitiframework
public WMSEntities() : base("name=WMSEntities")
{
}
already in autogenerated Model.Context.cs of edmx folder
To connect to multiple database in runtime, I created another constructor that takes connection string as parameter like below in same file Model.Context.cs
public WMSEntities(string connStringName)
: base("name=" + connStringName)
{
}
Now, I added other connection string in Web.Config for example
<add name="WMSEntities31" connectionString="data source=TESTDBSERVER_NAME;
initial catalog=TESTDB;userid=TestUser;password=TestUserPW/>
<add name="WMSEntities" connectionString="data source=TESTDBSERVER_NAME12;
initial catalog=TESTDB12;userid=TestUser12;password=TestUserPW12/>
Then, when connecting to database I call below method passing connetionString name as parameter
public static List<v_POVendor> GetPOVendorList(string connectionStringName)
{
using (WMSEntities db = new WMSEntities(connectionStringName))
{
vendorList = db.v_POVendor.ToList();
}
}
Hrmmm I happen to really like EF Code First but I'm not certain it suits what you're doing. How often does your schema change?
Should You Be Using EF?
Advantages of EF
If the schema changes somewhat regularly, the Migrations part of EF Code First might save you a lot of time and effort because you can often do away with SQL scripts for schema upgrades - schema changes end up in your source repository with the rest of your code instead. You'd start here:
https://stackoverflow.com/a/8909092/176877
I also happen to really like how easy EF is to setup, and how easy it is to write LINQ queries against it and return exactly the POCOs I built from the DB.
But EF might not be the best fit.
Other ORMs to consider
Many other ORMs support LINQ and POCOs with better support for existing databases (there are things that can be pretty difficult to map in EF Code First), --and existing support for asynchronous operation (EF is on 5.0 right now; 6.0 has async)-- (update: EF6 is the latest and its async support is great. Its bulk delete is terrible though and should be avoided like plague, drop to plain SQL for that).
In particular NHibernate is the beast on the scene for existing db support, but it's a bit of a configuration chore and what appears to be political infighting has caused the documentation to be conflicting for different versions and forks of it.
Much simpler are many "Micro ORMs" - that link is to a short list from 2011 but if you poke around you'll find 30 or so in .Net. Some generate better or less optimal queries, some none at all, some make you write SQL (don't use those) - you'll have to poke around to decide which is for you. This can be a bigger research task but I suspect the easy configuration and small learning curve for one of these best suits what you're trying to do.
Answer to your specific question
Talk to All client Dbs at once
If you're connecting to all 50 databases from one app at the same time you'll need to instantiate 50 DbContexts like:
var dbClient1 = new DbClient1();
var dbClient2 = new DbClient2();
Assuming you went around making little wrapper classes like:
public class DbClient1 : CoreDbContext
{
public DbClient1()
: base("DbClient1") // Means use the connection string named "DbClient1" in Web.Config
Where CoreDbContext is the main EF class in your Project that extends DbContext (standard part of any EF project).
Talk to just one at a time
If you're using just the one per app then any EF tutorial will do.
The only major trick will be migrating those Dbs when schema changes occur. Two basic approaches there. Either way you grab a backup and restore a copy of them locally so you can test your migrations against them (update-database -f -verbose). If you don't you risk data errors like changing a column to NOT NULL and finding your local test instance had no nulls, one client's did, kaboom. Once you get them working, you're onto deciding how you want to update Production. There are a lot of ways you might do this ranging from writing a custom roll-forward/back tool (or finding one) with SQL scripts checked into git, hiring a DBA, or much simpler:
The Obvious - SQL Script
Dump the migration to SQL (update-database -script) and run it against the actual production database.
My Crazy Way for Small Numbers of Dbs
Add entries for each db to Web.Config, and create a Project Configuration for each of them like "DbDeployClient1," "DbDeployClient2," etc. In each of those make a build define like DbDeployClient1, and then add this to your DbContext class:
public CoreDbContext()
#if DbDeployClient1
: base("DbDeployClient1")
#elseif DbDeployClient2
: base("DbDeployClient2")
// etc
#endif
{
That allows you to quickly switch to your DbDeploy config and run the migration directly from Visual Studio against the target database. Obviously if you're doing this you'll need to temporarily open a port, preferably only allowing in your IP, on the actual SQL Server instance you're migrating. One nicety is you get clear errors from your migration right there, and full rollback capability, without any real work - all that rollback support you're leveraging is just part of EF. And one dev can do it without a bunch of other bottlenecks. But it has a lot of opportunities to reduce risk and improve automation.

Silverlight, connecting to multiple databases on different servers

I'm developing a Silverlight 4 application (C#).
I used Silverlight Web application template and Entity framework to get started + VS 2010.
I now have a running application that connects to the database and displays data properly.
The database has one table with 5 attributes.
So what i need to do now..
I have a connection string to connect to a database on an external server. The database is similar to mine, but with more tables and updated information.I need to connect to this database. (EDIT: since this is outside my project i wont be having any EF for this but just privilege to query a single table. (VIEW to be specific))
Since I know the attribute names, table etc., use a SELECT query and get the data. So execute and get the result set. (E.g. "SELECT R.name, R.marks FROM results R").
The result set from query will be stored in, for example a data-table, and then insert into my database.
I also created an object class with accessors for the table, so that I can give the 'result set' the structure before I insert.
Theoretically this sounds possible when I chalk it on my board but I want to know if this would work?
I mean having 2 database connection open. Is this possible? If I follow the same steps as above can I achieve what I want?
Please let me know if I'm unclear about anything. This is just a smaller version of the real application but the logic i need to implement is the same. :)
If there is a better approach I'm happy to consider.
Cheers
You may be over thinking this a little. I add a new class project, and add a new ADO.NET Entity Model to that project using the connection string for the second database. After that, you'll be able to reference the new EF project from your Service or Host (Web) project.

Switching between databases in C# winforms

I made an application that generates reports based on data from a database.
The functionality of my application is correct, but I have a following problem: my client has 2 identical databases - one for testing and one for actual work he does.
My application should work with both databases (it should have a "switching mechanism"), but I don't know how to implement it.
I know that I could just switch between connection strings but the problem is that in my reports I use datasets that are bound to one database.
Is it possible to fill those datasets with the data from both databases (since the databases are identical in schema, it should be possible), and how would that be done, or do I have to use duplicate dataset/report pairs?
I'm using C# in VS 2010 with SQL Server 2005, and .rdlc for my reports.
Thanks.
Ideally you should should be able to change the connection string in one place and it should affect project-wide.
This will work ONLY IF you get the connection string from one place. Keep it in the app.config file.
See this article to see how you can store and read the connection string from the app.config file.
You've hit upon the reason why people implement the Repository pattern or at least a version of it.
You really need to remove your business logic away from the database, so that it is database agnostic. It shouldn't care where the data comes from only what it is.
From what you' said the implication is that your client doesn't wants more than just a change in the app.config connection string used for database access.
If that is so then, I know that it will entail some work, your best bet is to have a singleton pattern type class to control all data access to and from your data layer.
Using a known inteface you can use a factory pattern to create access to your development or live database at runtime (perhaps based on an app.config setting or even a test class that has no database access at all, but just returns hard coded test data.

Categories