Implementing TPH using "Database First" approach - entity-framework

I'm trying to implement EF TPH using the "Database First" with the help of the following document from Microsoft,
http://msdn.microsoft.com/en-us/data/jj618292.aspx
I do understand how this works but it sounds a little naive the way it's done or I'm missing something which I would like someone to enlighten me on this.
To my understanding, the whole point of implementing a database first approach is when you have a pre-exisiting database or if you prefer to do your work first hand on your database and work your way up, however, this document suggests that the inheriting tables (Student, Instructor) are meant to be created at the EF design area using a field on the base class which they call a "Discriminator" field which your inherited entities end up pointing to.
However, my question is, why would you have to create these inherited table at the ER designer where you initially intended to create your table structure first hand before working your way up the entity framework and how would this change that you applied on the ER designer (adding the inherited tables) be mapped into the back-end database, and at the end of the day when I want to make a change to my database later on, where will I have to make these changes (on MS SQL or the ER designer). If I end up adding tables from the ER end, then that would pretty much defeat the purpose of the "Database First" methodology, because I basically ended up using the procedures in the "Model First" approach which doesn't make sense at all.
Your help in clearing this up would be much appreciated.
PLEASE NOTE: I would rather have everything done at my database and rather not use the "Model First" approach. I'm interested to implement the TPH and be able to make any changes directly to my database and have those changes mapped into my EF sublayer (not the other way around).
Many Thanks

I don't see how EF could ever infer inheritance for you. Maybe it would be possible to have it triggered it by a field explicitly named "Discriminator" in a table, but what if you want a different name for the discriminator? And then, what should be the names of the derived classes? EF has no clue. The names are nowhere in the data model.
Still, it is database first. But EF just creates a first draft of the mapping. Nearly always you need to make modifications to the conceptual model (the model you see in the edmx), like renaming properties or classes, renaming/adding/removing associations. Or applying inheritance. When you update the the model from the database it may be necessary to apply some more manual changes. For instance, with TPH inheritance you may have to decide in which class to put a new field.
Maybe you are a bit side tracked by the idea that you "have to create these inherited tables at the ER designer". You define classes that map to one and the same table.

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 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 :)

design advice : Entity Framework useful with stored procedures?

I am new to .NET and early in the design process of a front-end application for a database, and looking for some advice.
I am not sure I get it...
The DB is very strongly normalized, but provides lots of stored procedures to abstract the logical model (ex. Select sproc returns one data set from multiple tables closely reflecting the business object, Insert/Update sprocs to multiple tables, etc..)
How should I design the DAL ?
I'm not sure what the benefit of the Entity Framework is in this context.
When generated, it reflects the normalized DB schema rather than an abstraction of it.
Or if I map the sprocs to generate it (which requires some work since the T-SQL in the sprocs is dynamic and with joins), I get the business objects alright but can't see the benefit of it : the entities represent to a single 'abstract' table, and not a set of entities with Datarelations, the sprocs handles the calls to multiple tables. It seems more work to map the generated change events to the sprocs than to call the sprocs directly.
What am I missing ?
Thanks,
Michael.
You can do this with the EF, but the designer won't help you; it doesn't know how to derive an entity type from a stored proc signature. You would need to write the EDMX by hand. CTP 4 code-first may be easier, but I've never tried it.
After some research, I think I'm starting to be on the right track.
The following articles were very helpful :
Entity Framework Modeling: Table Per Hierarchy Inheritance
see also : Entity Framework Modeling : Entity Splitting
To be clear, what I wanted was to abstract the DB schema in the EF model.
(I didn't want any entity representing 'nothing', like a many-to-many relationship).
Besides these modeling techniques, I used views to generate the EF model, and added sprocs for CRUD.
As I said, I am a beginner. Let me know if I am on a wrong track...

Entity Framework: Modeling against an existing database scheme

I've been scratching my head over this for over a week now and haven't gotten anywhere :( We have an existing legacy DB that I'm trying to model my entities against. The tables are extremely bloated and we do not have enough bandwidth to create new, optimized tables. So I'm having to work with what we already have. However, I do not want to use all the redundant columns that are exposed by the DB. My initial plan was to use Views in my Model but that is looking to be equally hairy with very little documentation around.
Now, what would be the best way to go about creating a Model with just a select few columns? All I need is a bunch of read-only entities; so if there is a way to ignore non-nullable columns from the schema, I'd be all set. I was planning on making use of POCOs else I'd have to create my own mappings I reckon.
UPDATE: By POCOs, I mean I'd like to use the ADO.NET POCO Entity Generator.
What about creating views in the DB, and only importing the views into the model?
Well, if you need only a bunch of entities and if they won't change a lot during time, than I would just pick the tables you need, generate the entities with the normal wizard and all collumns, and than delete all not needed collumns manually in the model designer.
add the table to your EF, and just delete the properties you don't want. it just won't map those DB fields.