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

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.

Related

Combine Code First & Database First In Single Model?

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.

Entity Framework 7 and EDMX manipulation to auto-generate custom code

I currently use EF6 and use the model first approach. As I understand it, EF7 will be moving away from using an EDMX, and going from a more code-first approach. Now I know I will still be able to reverse engineer from my database into classes if need be.
However one thing I am not sure about is any manipulation I currently do with EF6 will be supported in anyway in EF7.
At the moment, I write T4 templates that read through the EDMX, pick up on the entities, and create new classes based on them. For example, I create partial classes for each entity that has deep clone methods in them. I also create repository classes based on the entities and create methods for finding by primary key, based on which properties in each class have been identified as the primary key.
If I lose the EDMX, does this mean I need to go back to manually creating these? Or is there another way?
If you want to keep using T4 templates, you can switch to something like CodeFirst -> ReverseEngeneer approach.
You update model in code, generate new migration, test it on a database and then use a reverse engeneer code first approach (http://msdn.microsoft.com/en-US/en-en/data/jj593170.aspx) to generate everything else. Theoretically it can be automated.
In my team we do it manually, but we do not need migrations, only a code first contexts and a lot of additional things, that T4 generates whery well.
Yes, you can still use T4 templates with Code First, We navigate Entity Classes instead of the EDMX Model, .
I have been looking at VS2015 recently and having some issues with T4 and asp.net 5 and related projects (FileManager hangs for multiple file outputs and you will need the latest version of Visual Studio, currently Update 1)

Sharing entity types across multiple edmx files

We are using Entity Framework 4 with the POCO Entity Generator. Until now we've just had one .edmx file but we're running into performance problems due to the current size of it (well over 100 entities).
I understand we should be looking to break this into a series of .edmx files which is fine with one exception. We would want to somehow share certain entity types across two or more of these contexts. For example a User class is associated with numerous otherwise unrelated entities throughout our model.
So is it possible to have, say, a security model with its own .edmx and namespace for generated POCOs, but use it in another .emdx? If not I'm concerned we'll have multiple classes modelling the same database table which will need to be updated in sync with the database. I'd say that would be unworkable. (We're using database-first).
Obviously if I'm barking up the wrong tree do let me know!
In theory you can have single POCO class used with multiple EDMX mappings because the mapping and class must match only in the name and name/types of properties. In practice this has some limitations. Just few I can think about:
You cannot use automatic code generators with this approach unless you modify generator for every EDMX and make sure that every entity will be generated by just single generator from single EDMX. This directly points to second limitation.
Entity must be exactly same in every EDMX. Including navigation properties. If it is not you will not be able to generate it at all without building your own code generation solution. What is worse if dynamic proxies demand that class with unique name is mapped only once. If you have two or more different mappings for the same class you will not be able to use dynamic proxies (lazy loading, dynamic change tracking) with only single mapping per application run.

Managing Entity Framework at Enterprise Projects (with hundred of tables)

I am using Entity Framework at my work and faced some problems.
Usually I hear about creating tiny Edmx´s files containing tables related to some Domain ie.: Help Desk Edmx, HR Edmx, etc. Instead of load all tables in one big Edmx, what would be much simpler, but for performance considerations(at design and build time mainly), it isn´t feasible.
It took me to some troubles, first about the commom tables, ie.: Employees Tables, it is at all Edmx´s, conflicting when I use a Employee class reference and have a using to both namespaces, then I have to reference the Empoyee class by the full name MyCompany.HelpDesk.Employee.
It doesn´t look natural.
I find myself repeatedly adding the same tables at all EDMX´s, it´s a rework, and I spend some minutes adding a table to entity framework design since I have 2k tables at Add Table Dialog.
Maybe VS2012 could be a solution to load 2k Tables at the same Edmx file(since the designer could be splitted), but I don´t believe that, because it delay to compile too, not only to open the designer.
Another option could be the Code First, but it doesn´t have a decent tool to Reverse Engineer the database to classes, since it tries to load all the tables from database, tooking about 2 hours!
There is generally no solution for your problem. EF supports some way to share common entities across multiple CSDL files but it has a lot of disadvantages:
It is not supported by designer (I didn't try if VS2012 designer support this) -> you are going to maintain EDMX files as XML
It is supported only on CSDL level (classes) -> you still have single SSDL (tables) and MSL (mapping) and you must maintain them manaully
Only unidirectional relationships to shared entities (shared entity can have navigation properties only to other shared entities).
VS2012 will allow you working with multiple diagrams in single EDMX but I really don't know how fast this will be with 2k tables.
IMHO 2k tables doesn't sound like use case for EF mapping features - especially not for features where you expect the code to be generated for you. Large scale development usually involves large scale coding or developing your own tools. Your current way (by mapping shared entities again) is the best approach with default EF tooling.
If you use T4 generator for POCO classes you can even modify T4 template to use always the same class for all EDMX files. POCO classes are mapped only by class names - namespace doesn't make any difference. This will require you to put some effort into T4 generator to make sure that shared classes are generated only once and correctly referenced from all your model specific classes.
Btw. how much time does it take to start your application and load all your mappings? Are you using pregenerated EF views?

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.