Entity Framework - Multiple Database Connections - c#

I have used Entity Framework code first with good results.
The project uses a second, legacy database which is already designed and running.
I'd like to call both databases in the project. Does any one have any suggestions of the best solution to do this?
I have done both seperatly (in tutorials) but never both. Yes its not the best idea to connect to two databases but each database has distinctly different datasets.
I am already using EF Code first and have been using POCO classes. Would you suggest creating a EDMX file as well? Assume would need two db context files?

I have done several solutions where there was a Code First connection and a Database First connection used in the same project without any issues. I would do as you stated, just create the edmx for the existing database.
I generally create one library project for each database and reference them from the main app project, just to help keep things from getting mixed up.
You just instantiate a context for each database and use them just as you would with a single context. They act as completely separate, independent repositories.

Related

C# Is there an easier way to create a database, empty tables, tables with data in them by default, stored procs and views?

Before I posted this question, I did some Googling first on how a database was created through C# and mostly it points to either SMO or SQL query files and it was the time of SQL Server 2005 and 2008.
So at this day in age, is there an easier way to create a database with empty tables, tables with data in them by default, stored procedures and views?
I need a suggestion.
I think the answer is probably Entity Framework. You can do 'code first' and use database migrations, allowing you to write your C# code and use that to generate a lot of the database for you.
Ultimately though, 'easier' is subjective. I personally find EF great for the 'normal' stuff, but at the end of the day, if you need a stored procedure to do some custom logic; you need to write the custom logic, in some fashion.
Maybe have a look and see if you think it fits your needs.
https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Looked at the database projects in studio 2013. You create a database as a series of scripts using a familiar GUI. However, changes are published - this process creates a unique change script targeting the connection you define. For new databases the whole thing gets created, but publish against a partial or out dated version and the script created in a change script to bring it up to date.
You can even writ unit tests against your database using specialist tools, although I do find them lacking a bit.
More on msdn - here
Depends. right out of gates. Sp and views. Best shot is directly from database through a workbench. I can then capture definitions and store in a file to be replayed through c#
As for tables there are many orms that can generate tables via c#. Look at entity frameworks. Code first examples
I have generated tables using EF Works fine. I then went into database and created views and sps.
The trick is to migrate new views and sps into your EF model U can google entity Frameworks code first ... Adding views and SPs.
Worst case is u create database all through database workbench. Create a script that an be played to recreate eveything. By running. Then use EF DATABASE first approach
In either case u end up with a good set of autogenerated code to manage CRUD and object management and an abstracted data model

How to use Entity Framework code-first with a newer database model version

Maybe an odd question, but we have a scenario in which we want to use Entity Framework code-first in an environment which could have a database with a newer/higher version than the code itself.
Let me elaborate a bit. We have a couple of solutions which all use a core assembly which contains the overall datamodel which all solutions are using. The solutions are mainly sites and apps which are deployed to several different Azure Web Sites. So the solution are running next to each other. The only thing they are sharing is the Azure database.
Now the scenario will come in play. When we update the database model in the core assembly and update one of the solutions in Azure. The underlying database will be updated when the model is loaded within that solution. No problem there, works like a charm...
The problem starts when one of the other solutions is loaded. These other solution are still using the previous core assembly which has now an outdated EF CF model compared to the database model they are connecting with. So a nice exception will be throw as shown below.
The model backing the '{NAME}' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.
The question is whether we can force the model just to load and ignore the changes made within the database. We internally have a policy to only apply not breaking changes within the database, so the model should be able to load without any problems.
Thanks in advance for the information and tips!
I can be wrong(not sure whether I remember correctly), but if it doesn't interferes with your application configuration, you can set DB initializer to null:
public PortalDbContext()
: base("name=PortalConnectionString")
{
Database.SetInitializer<PortalDbContext>(null);
}
Or it could be possible to create custom initializer:
public class BlogContextCustomInitializer : IDatabaseInitializer<BlogContext>
{
public void InitializeDatabase(BlogContext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(true))
{
// Do something...
}
}
}
}
If you're using EF Code-First, the model must match the database.
Even if you found a way to circumvent that limitation you'd be doing something dangerous.
Let me expalin it: if you update the database from "Solution A", the model in "A" will match the database, and any further changes to the model in this solution can be applied to the database without any problem at all. That's right!. However, if you do what you're asking in this question, i.e. you do something so that "Solution B" can keep working even if the model doesn't mathc with the DB, and then you make a change to the model in "Solution B", how do you apply it? how can "Solution B" know what changes to apply? how can "B" determine what changes made by "A" should be left as they are, and what are the new changes made by "B" that must be applied to the database?
If you could follow on like this, you'd finish with two different code first models, none of which matches the database, and, besides, how could you warranty that both applications work correctly? how can you ensure that changes on "A" doesn't affect code on "B" and viceversa?
The safest solution to avoid this problem is to share the assembly containing the code first model between both solutions. Any other solution will be troublesome sooner or later. Perhaps you'll have to refactor your solutions so that they can share the same DbContext. The DbContext must be the only thing in your project. I usually have an Entities project, and a DbContext project which has a reference to Entities. Then both solutions would have references to these projects. These projects can be in one of the solutions, or in a completely different solution. Of course in one, or both solutions, you'll have to add a reference to the DbContext assembly, instead of the project, and keep it updated, for which you can use post-build scripts. In this way, when you recompile your solutions you'll also detect incompatible changes made for one solution which adversely affects the other.
EF6 supports several different DbContexts in the same database, so, if each of your applications had a different, non conflicting DbContext, you wouldn't have a problem. I cannot check it right know, but I think that the name of the DbContext must be different in each solution (I don't remember if the namespaces are taken into account). By non conflicting I mean that they refer to different database objects (tables, views, or whichever), of that the objects refered to by both contexts are not changed (for example master tables).

What type of c# project should an SSDT model be placed in?

Sorry if this is a totally noob question but I just can't seem to find a starting point on this.
From what I've gathered so far SSDT was developed with the idea that it would be used in a different project that that of the main app for database related coding. I figured that instead of complaining about how much I like the old version back, I'd try things their way and see how well it goes but I can't seem to get a handle on where to begin over here.
Basically I want to use a code first approach and create a database from a designer. If I'm going to create a new project to handle the entity framework, what type of project should it be? a C# class library, WPF.. something else?
I'm not sure if it's of any relavance but the app I'm working on is a WPF app and the database is MySQL.
If you want to use a code-first approach, then that means that the database will be generated by the code. Thus, you will not have a separate database-project, since that would mean that your database is kept in two places. Therefore, your options are:
Use code-first. This usually means a class library (although asp.net mvc usually has the context with entities in the asp.net mvc project, let's call that an exception to the rule). The class library will contain classes with which your database will be generated.
Use a database project, an SSDT project. Your database will be defined here, and when you deploy this project the database will be generated/updated.
Note: AFAIK an SSDT project is specific to SQL Server, so since you are using a MySql database it is not an option.

Work flow using Code-First -vs- DB-First in starting a new project? EF6

When creating a new solution (typically ASP.Net MVC or API) I usually create a data access project and my web project. In the data access project I typically use EF6 and have been trying to use Code-First so that I can take advantage of the migrations feature.
In the data access project I create a model folder and then in that folder add my classes and my DBContext class. Then I generate my migrations and seed data. This all works ok.
What I was wondering are there more efficient ways of creating this
type of project?
Am I hampering my productivity by going code first?
I know I am not using code generation that the database first process
would use. Can I gain efficiencies by switching to DB first?
What are typical work flows that others use?
OR is there a hybrid approach that people find successful?
I understand that this has been addressed in other posts but my questions is more in context of EF6 and those all seem to be based on EF4.
TIA

What's the best way to reuse database access across multiple projects to ensure that when updated it does not break any projects?

I have probably written the same LINQ to SQL statement 4-5 times across multiple projects. I don't even want to have to paste it. We use DBML files combined with Repository classes. I would like to share the same Library across multiple projects, but I also want to easily update it and ensure it doesn't break any of the projects. What is a good way to do this? It is OK if I have to change my approach, I do not need to be married to LINQ to SQL and DBML.
We have both console apps and MVC web apps accessing the database with their own flavor of the DBML, and there have been times when a major DB update has broken them.
Also, since currently each project accesses the DB from itself, which is sometimes on another server, etc. Would it be possible to eliminate the DB layer from being within each project all together? It might help the problem above and be better for security and data integrity if I could manage all the database access through a centralized application that my other applications could use directly rather than calling the database directly.
Any ideas?
The way I handle this is using WCF Data Services. I have my data models and services in one project and host this on IIS. My other projects (whatever they may be) simply add a service reference to the URI and then access data it needs over the wire. My database stuff happens all on the service, my individual projects don't touch the database at all - they don't even know a database exists.
It's working out pretty well but there are a few "gotchas" with WCF. You can even create "WebGet" methods to expose commonly used methods via the service.
Let me know if you want to see some example code :-)

Categories