Combine Code First & Database First In Single Model? - entity-framework

Is there a way to combine code-first and database-first in the same context? We are running into massive development-time performance problems when editing the EDMX file (it takes 1.5 minutes to save). I've moved our non-insert/update/delete UDFs/stored procs to some custom T4 templates that automatically generate model-first code, but I can't seem to get OnModelCreating to be called when EDMX is involved.
Other things we've considered, but won't work for one reason or another:
We can't (reasonably) separate our code to multiple contexts as there is a lot of overlap in our entity relationships. It also seems like quite a people who have gone this route regret it.
We tried having 2 different contexts, but there are quite a few joins between Entities & UDFs. This may be our last hope, but I'd REALLY like to avoid it.
We can't switch to Dapper since we have unfortunately made heavy use of IQueryable.
We tried to go completely to Code-First, but there are features that we are using in EDMX that aren't supported (mostly related to insert/update/delete stored procedure mapping).

Take a look at the following link. I answered another question in a similar fashion:
How to use Repository pattern using Database first approach in entity framework
As I mentioned in that post, I would personally try to switch to a Code First approach and get rid of the EDMX files as it is already deprecated and most importantly, the maintenance effort is considerable and much more complex compared with the Code First approach.
It is not that hard switching to Code First from a Model First approach. Some steps and images down below:
Display all files at the project level and expand the EDMX file. You will notice that the EDMX file has a .TT file which will have several files nested, the Model Context and POCO clases between them as .cs or .vb classes (depending on the language you are using). See image down below:
Unload the project, right click and then edit.
See the image below, notice the dependencies between the context and the TT file
Remove the dependencies, the xml element should look like the image below:
Repeat the procedure for the Model classes (The ones with the model definition)
Reload your project, remove the EDMX file(s)
You will probably need to do some tweeks and update names/references.
I did this a few times in the past and it worked flawlessly on production. You can also look for tools that do this conversion for you.
This might be a good opportunity for you to rethink the architecture as well.
BTW: Bullet point 4 shouldn't be a show stopper for you. You can map/use Stored Procedures via EF. Look at the following link:
How to call Stored Procedure in Entity Framework 6 (Code-First)?

It also seems like quite a people who have gone this route [multiple contexts] regret it.
I'm not one of them.
Your core problem is a context that gets too large. So break it up. I know that inevitably there will be entities that should be shared among several contexts, which may give rise to duplicate class names. An easy way to solve this is to rename the classes into their context-specific names.
For example, I have an ApplicationUser table (who hasn't) that maps to a class with the same name in the main context, but to a class AuthorizationUser in my AuthorizationContext, or ReportingUser in a ReportingContext. This isn't a problem at all. Most use cases revolve around one context type anyway, so it's impossible to get confused.
I even have specialized contexts that work on the same data as other contexts, but in a more economical way. For example, a context that doesn't map to calculated columns in the database, so there are no reads after inserts and updates (apart from identity values).
So I'd recommend to go for it, because ...
Is there a way to combine code-first and database-first in the same context?
No, there isn't. Both approaches have different ways of building the DbModel (containing the store model, the class model, and the mappings between both). In a generated DbContext you even see that an UnintentionalCodeFirstException is thrown, to drive home that you're not supposed to use that method.
mostly related to insert/update/delete stored procedure mapping
As said in another answer, mapping CUD actions to stored procedures is supported in EF6 code-first.

I got here from a link in your comment on a different question, where you asked:
you mentioned that code-first & database-first is "technically possible" could you explain how to accomplish that?
First, the context of the other question was completely different. The OP there was asking if it was possible to use both database-first and code-first methodologies in the same project, but importantly, not necessarily the same context. My saying that it was "technically possible" applies to the former, not the latter. There is absolutely no way to utilize both code-first and database-first in the same context. Actually, to be a bit more specific, let's say there's no way to utilize an existing database and also migrate that same database with new entities.
The terminology gets a bit confused here due to some unfortunate naming by Microsoft when EF was being developed. Originally, you had just Model-first and Database-first. Both utilized EDMX. The only difference was that Model-first would let you design your entities and create a database from that, while Database-first took an existing database and created entities from that.
With EF 4.1, Code-first was introduced, which discarded EDMX entirely and let you work with POCOs (plain old class objects). However, despite the name, Code-first can and always has been able to work with an existing database or create a new one. Code-first, then is really Model-first and Database-first, combined, minus the horrid EDMX. Recently, the EF team has finally taken it a step further and deprecated EDMX entirely, including both the Model-first and Database-first methodologies. It is not recommended to continue to use either one at this point, and you can expect EDMX support to be dropped entirely in future versions of Visual Studio.
With all that said, let's go with the facts. You cannot both have an existing database and a EF-managed database in a single context. You would at least need two: one for your existing tables and one for those managed by EF. More to the point, these two contexts must reference different databases. If there are any existing tables in an EF-managed database, EF will attempt to remove them. Long and short, you have to segregate your EF-managed stuff from your externally managed stuff, which means you can't create foreign keys between entities in one context and another.
Your only real option here is to just do everything "database-first". In other words, you'll have to just treat your database as existing and manually create new tables, alter columns, etc. without relying on EF migrations at all. In this regard, you should also go ahead and dump the EDMX. Generate all your entities as POCOs and simply disable the database initializer in your context. In other words, Code-first with an existing database. I have additional information, if you need it.

Thank you to everyone for the well thought out and thorough answers.
Many of these other answers assume that the stored procedure mappings in EF Code-First work the same, but they do not. I'm a bit fuzzy on this as it's been about 6 months since I looked at it, but I believe as of EF 6.3 code first stored procedures require that you pass every column from your entity to your insert/update stored procedure and that you only pass the key column(s) to your delete procedure. There isn't an option to pick and choose which columns you can pass. We have a requirement to maintain who deleted a record so we have to pass some additional information besides just a simple key.
That being said, what I ended up doing was using a T4 template to automatically generate my EDMX/Context/Model files from the database (with some additional meta-data). This took our developer time experience down from 1.5 minutes to about 5 seconds.
My hope is EF stored procedure mappings will be improved to achieve parody with EDMX and I can then just code-generate the Code-First mappings and remove the EDMX generation completely.

Related

Trying out Entity Framework Code-first; is the usage any different from Database-first?

When working with EF (v4,5,6) I have always used Database-first (I was mistakenly under the impression this was the only way to generate Entities from existing tables, EDMX, etc). But today I tryed Code-first, and it can also generate the POCOs (in a different way, no EDMX, different connection string, less cr8p lying around, etc..!)
So far, the usage of EF for CRUD appears to be exactly the same, can anyone who has used both please confirm there is nothing different (in usage), or gotchas I should be aware of?
And a supplementary question is, can I generate both in the same project ? (Not that i want to, but existing proj has EDMX within a folder, can I create another folder and generate Code-First Entities (different set of tables only), so i end up with DBContext and DBContext2 ?
Yes, the usage is the same. If you check the generated code you'll see they use the same System.Data.Entity.DbSet properties and they both inherit from the same System.Data.Entity.DbContext class.
Yes, you can generate both in the same project, but does not makes much sense, because you have to maintain both of them if the DB changes.

Code First Existing Database vs EF Designer to Existing Database

We are starting a new large corporate project. The database will be 100+ tables and we will be using Entity Framework, Web API and MVC.
My question is specifically related to the Entity Framework aspects of the solution.
I am trying to make a choice between the following:
Code first to an existing Database
EF Designer to an Existing Database (Database First)
I know we can use EF to generate the database from code first or from the EF designer, but we prefer to have full control over the database and develop that in the traditional way, so we have excluded the EF options that allow us to auto-generate the database.
Most of what I can find on the internet relating to Code First deals with creating a new database and then using code migrations. And when the discussions deal with Database first then the discussions favour the EF Designer. Example here: Code-first vs Model/Database-first
My preference is to go with the combination of Code First to an existing database.
The following are my considerations for favouring this option and I'm wondering if there is anything else I need to consider, and whether my assumptions/thoughts are correct.
Code first to an Existing database
There will be a large number of classes to construct at the start, but we could do the initial generation from the EF Model Wizard.
The classes could then modified with any custom properties or to remove anything we don't need, rather than the EF Designer that would require us to extend any classes.
The disadvantage is that any changes to the database would have to be manually added to our classes, unlike using the designer which will allow easy updating.
Edit:
I think I was confused in this area. From reading, it appears that the correct way to do Data First is to create partial classes for all the auto generated classes, and then to make any modifications to the partial classes as part of the 'business' layer.
My thought has therefore changed from favouring the Code First from Database, to using the EF Designer to existing database and then creating the partial classes.
In any case you'll have to synchronize the EDM (entity data model) and the DB. You have to make sure that the EDM is fully compatible with your database. If not, it will fail, no matter if it's Code First or you use a Model.
The only difference is that:
using the designer you can do it graphically, and easyly set properties, column names, and so on
using Code First, you have to set these properties, columns names, data types and so on using conventions, Fluent API or attributes
With Code First the only advantage is that once you've synchronized the Code First model (see "Code First is also an EDM, but somewhat limited") and the database, you can start using Migrations, and evolve your model using them, which later makes it easier to apply changes to the production DB (whenever a new version is released). With graphic model you cannot use migrations, and have to upgrade the Db directly from Visual Studio, or creating SQL DDL scripts by hand.
Code First is also an EDM, but with a few missing functionalities
It doesn't matter if you use Code First or draw a model, an EDM (entity data model) will be generated. If you're used to design databases, probably you'll be more comfortable using the designer. Beware of the notes on EF Core (former EF7) below!.
However, the EDM generated by Code First has a few limitations that the designer doesn't have.
The most outstanding limitations of Code First is that in the designer you can easily map user defined functions from the BD, for example scalar and table value functions, and stored procedures. With Code First there are much more limitations.
in EF 6.1 most of this limitations dissapear, but it's still a bit difficult to make the mappings.(In fact, as of today, 2014, there's only a sample, and a simple Nuget package on how to do it.).
As of march 2017, non-Core EF, i.e. EF 6.1, is no longer being updated. MS will probably solve bugs if they appear, (this was wrong: but don't expect further changes)
New features appeared in 6.2: What's new in EF 6.2, which includes definition of indices with Fluent API, support for Like, support for non-identity DB generated keys, like SEQUENCE and some other changes
Changes on EF Core, former EF7 (as of may 2015)
At this time Microsoft is developing EF 7, but it's also maintaining EF 6.x. The current recommendation is to keep using EF 6 for some time, because EF 7 is not mature enough.
EF 7 is being developed from scratch to overcome the inherited ObjectContext which was posing terrible limitations to implemente new features. But it implements the most widely used DbContext with little changes. So, if you use DbContext you'll have an easy migraiton path to incoming new versions of EF.
However there is a very important change: in EF Core (former EF7) the EDM model dissapears in favor of Code First models. So, if you want to use the technology of today and assure an easy upgrade to new versions, don't use Model First or Database First: use Code First. There are important reasons for Microsoft to have taken this decision: Code First works much better in a team environmet with version control, and allows to work with Migrations. Anyway tou can still see the model in a graphical way (with Power Toools) or use a third party tool to create the model using a designer (several of the current commercial solutions will support this for EF7).
NOTE: Why is much better Code First in team environments? If several team members modify the model it's much easier to merge changes in several code files, than in a big XML file, with lots of lines which defines the model. It's also much harder to understand the changes between versions in this hugh XML file. For medium or big projects, I recommend you to move to Code First ASAP

Entity Framework Code First with an existing database

I have to create a new project and (as usual) is with an existing SQL Server database.
I used to use EF Code First connecting with my database, opening my EDMX model designer and then right click --> Add Code Generation Item. (http://weblogs.asp.net/jgalloway/archive/2011/02/24/generating-ef-code-first-model-classes-from-an-existing-database.aspx) Easy.
But now I've discovered there's something called EF Power Tools that allows me to do Reverse Engineer Code First (cool name!) and get the same (http://msdn.microsoft.com/en-us/data/jj200620)
Do you know the difference between the two options? Which one is better?
Thanks in advance.
(Sorry if this question was previously asked but I didn't find it.)
The difference is that the edmx approach is not code first, but database first with DbContext API. You will always use the database as the source of model changes.
EF Power Tools produce a truly code first model with DbContext: from then on you will change the class model first and modify the database accordingly (e.g. by EF migrations).
Neither is "better". DbContext API is easier to work with than ObjectContext, but both approaches use the former. It's up to you to choose whether you want to work database first or code first. It's a matter of personal preference and it may depend on who maintains the database structure. With database first it is easier to respond to changes someone else imposes on the database structure.
As far as workflow goes for database first, adding to what #Gert-Arnold said:
With database first it is easier to respond to changes someone else imposes on the database structure.
If someone else is managing the database changes, I'm finding it far easier to use the EF Designer. You get an updated database, then just right-click in the EF Designer and update the model from the database. You can use source control to easily view what has changed.
Also, if you only need a subset of tables from the database, reverse engineering causes alot of work having to go back and remove classes and properties from the context.
I found re-reverse engineering via code-first to an existing database to be just too much of a pain trying to figure out what changed and how I needed to update code that used the context.

Have anyone used Entity Framework with code first approach mixed with Edmx file?

I'm currently assign to a project where their legacy system is designed in a horrible way and it's been too much focus on database design. I trying to put together a new design where the customer can migrate the legacy system bit by bit.
They are currently using EF 4.1 BUT not code first approach with entity descriptive/mapping is located in an edmx file. They do Reverse engineering everytime to want to extend the model (First make changes in database, then reflect them upwards to Model layer through a custom tool).
What I would like to know, if anyone has used BOTH edmx and code first approach with mapping classes. And is there drawbacks to know about?
You can use EDMX and code mapping together only if you have separate context type for each approach (you cannot mix approaches in single context type). That is probably the biggest disadvantage because it leads to more complex code and maintenance.
For example if you need to have some entity in both contexts types to use it with both new and legacy code you must maintain its mapping twice. You must also be very careful about not duplicating entity class itself = your code first must use class generated by custom tool for EDMX but this will not be possible if they are not using POCOs in current solution.
Another problem will be database integrity. If you will need to save changes to both context types in single transaction you will have to use TransactionScope and distributed transaction = MSDTC (each context instance will handle its own database connection).
If you are sure that whole system will be migrated you can probably think about using code first instead of EDMX (but be aware that code first mapping and DbContext generally offers more limited feature set). If you are not sure that you will be able to complete whole migration don't even think about using code first because leaving system in the state where half uses code first and half EDMX will make everything only worse and much more horrible.
Being sure is little bit theoretical because in SW development the only think you can be sure about is that requirements / situation will change. It means that migration should be very carefully considered.
I also was struck with this problem. What I found was that you can model the database and "generate the database from the model" in a "Ado.NET Entity model Project".
But you can not create stored procedures in that project, What only you can do is you can import the stored procedures from the server.
But if you do not want to create stored procedures on the server, you can create another project on VS, "SQl CLR Database Project" and you can code your stored procedures and tigers in that project and deploy them to the server.
then you can again import these stored procedures from the "Ado.NET Entity model Project" by "Update Model From Database".
Like wise you can develop your server project using both approaches(Code first and Model first)
Hope this will add something more :)

EntityFramework withour EDMX

We are about to start using EF as our ORM. We have our own MetaData representing the databse stracture and we will generate whatever we need off of that.
We are wondering whether to use the "old" EDMX approace, or to use the new EDMX free approach (wiht DbSet and DbContext). As we do our own code/edmx generation it seems odd to generate an EDMX and then generate objects and context off of it.
The thing is I don't see much talk about about the EDMX free approach. Is it being used by anyone? Can someone with experience share their impressions? Are there known limitations? Are there pros and cons?
Asher
Are you asking if anybody is using code-first? :) By checking the number of questions in entity-framework-4.1 and code-first and ef-code-first I guess people are using it a lot. There were several questions about code-first x non code-first. Some of I answered:
EF POCO code only VS EF POCO with Entity Data Model
EF Model First or Code First Approach?
EF 4.1 Code-first vs Model/Database-first
Generally there are four approaches:
Model first (database generated from EDMX)
Database first (EDMX generated from database)
Code first (database generated from code mapping)
Database first with code mapping (code mapping manually created for existing database or manually updated mapping generated by EF Power Tools CTP)
Selection of the approach usually depends on the way how you want to develop application (as described in linked answers). It also depends if you want to use ObjectContext API or DbContext API. The former one is usually used with first two approaches (but the secret is it should work with code-first as well) the later one with all of them.
Code first has some limitations - it doesn't support all mapping features EDMX does for example:
Stored procedures mapping (it doesn't mean you cannot execute SP when using code first)
SQL functions mapping
Advanced EDMX features like defining queries, query views, model defined functions
etc.
What I don't understand is why are you trying to combine your code generation tool with EF. Either use your stuff or use EF's stuff. You will avoid complications and incompatibilities.