Generating SQL Server Views from EDMX using T4 templates - entity-framework

I'm working with a legacy database that I can't easily create an entity model over because it uses extension tables with what is effectively composite keys and EF only supports single column keys for mapping one entity to multiple tables.
So, what I've decided to do is create updatable views (with INSTEAD OF triggers to handle CRUD operations) over the top of the legacy tables (which cannot be touched) and then have my entity model (either using EF or DevExpress XPO) built on top of the database views. This will also allow me to do stuff like easily add sub-queries in the select clause to retrieve child counts on parent records when retrieving a list of parent records in a single query.
However, I don't particularly want to manually write the SQL for all the views and triggers so I thought I'd use data model defined in the .EDMX file and t4 templates to help me generate the bulk of the T-SQL needed to create the views and the triggers. I thought there would be some template that I could use as the basis for doing this, but seems that's not so easy to find.
Can someone please suggest a t4 template that I could use as the basis where mappings are being retrieved from the .EDMX. Alternatively can anyone advise how to use the StorageMappingItemCollection to retrieve the mapping information from the EDMX file. I know a few people have said that apparently you can't use it or that they just use Linq to Xml, but I would have thought it should certainly be possible to use the StorageMappingItemCollection class as a strongly typed class to access this data.
Any examples of how I could use StorageMappingItemCollection to access mapping info would be very helpful. Thanks.

See http://brewdawg.github.io/Tiraggo.Edmx/ you can install it via NuGet within Visual Studio and it serves up all of the metadata from your EDMX files that Microsoft hides from you, very simple, works great.

Related

Development process for Code First Entity Framework and SQL Server Data Tools Database Projects

I have been using Database First Entity Framework (EDMX) and SQL Server Data Tools Database Projects in combination very successfully - change the schema in the database and 'Update Model from Database' to get them into the EDMX. I see though that Entity Framework 7 will be dropping the EDMX format and I am looking for a new process that will allow me to use Code First in Combination with Database Projects.
Lots of my existing development and deployment processes rely on having a database project that contains the schema. This goes in source control is deployed along with the code and is used to update the production database complete with data migration using pre and post deployment scripts. I would be reluctant to drop it.
I would be keen to split one big EDMX into many smaller models as part of this work. This will mean multiple Code First models referencing the same database.
Assuming that I have an existing database and a database project to go with it - I am thinking that I would start by using the following wizard to create an initial set of entity and context classes - I would do this for each of the models.
Add | New Item... | Visual C# Items | Data | ADO.NET Entity Data Model | Code first from database
My problem is - where do I go from there? How do I handle schema changes? As long as I can get the database schema updated, I can use a schema compare operation to get the changes into the project.
These are the options that I am considering.
Make changes in the database and use the wizard from above to regenerate. I guess that I would need to keep any modifications to the entity and/or context classes in partial classes so that they do not get overwritten. Automating this with a list of tables etc to include would be handy. Powershell or T4 Templates maybe? SqlSharpener (suggested by Keith in comments) looks like it might help here. I would also look at disabling all but the checks for database existence and schema compatibility here, as suggested by Steve Green in the comments.
Make changes in code and use migrations to get these changes applied to the database. From what I understand, not having models map cleanly to database schemas (mine don't) might pose problems. I also see some complaints on the net that migrations do not cover all database object types - this was also my experience when I played around with Code First a while back - unique constraints I think were not covered. Has this improved in Entity Framework 7?
Make changes in the database and then use migrations as a kind of comparison between code and the database. See what the differences are and adjust the code to suit. Keep going until there are no differences.
Make changes manually in both code and the database. Obviously, this is not very appealing.
Which of these would be best? Is there anything that I would need to know before trying to implement it? Are there any other, better options?
So the path that we ended up taking was to create some T4 templates that generate both a DbContext and our entities. We provide the entity T4 a list of tables from which to generate entities and have a syntax to indicate that the entity based on one table should inherit from the entity based on another. Custom code goes in partial classes. So our solution looks most like my option 1 from above.
Also, we started out generating fluent configuration in OnModelCreating in the DbContext but have swapped to using attributes on the Entities (where attributes exist - HasPrecision was one that we had to use fluent configuration for). We found that it is more concise and easier to locate the configuration for a property when it is right there decorating that property.

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)

Adding Hand-Built Models to an EDMX

I'm following an MSDN article on applying the Repository Pattern and the Unit Of Work Pattern to Entity Framework, but I'm stuck at the mapping between the custom-made domain models and the as-yet-nonexistant database.
The article has me create two simple POCOs, Employee and TimeCard. It also walks through creating generic repositories and custom implementations therein. (I'm using the custom repositories so I can try to keep EF dependencies in the data access assembly.) However, they sort of glaze over an important step in the mapping. The article says:
With the POCOs in place we can create an Entity Data Model (EDM) in Visual Studio (see figure 1). We will not use the EDM to generate code for our entities. Instead, we want to use the entities we lovingly craft by hand. We will only use the EDM to generate our database schema and provide the metadata EF4 needs to map objects into the database.
The "Figure 1" it references is here:
But that's all it says on the subject. There's an aside on how to generate POCOs from an EDMX. There's lots of information via Google on how to generate POCOs, generate EDMX from a database, etc. But in this walk-through we already have the POCOs and I need to use them in the EDMX which would, in turn, generate the database (I'm assuming, based on other code-first walk-throughs).
I've added an "ADO.NET Entity Data Model" to the project, which is basically a blank canvas. But I'm not seeing how to add my existing POCOs to that canvas. Do I have to re-create them manually on the design surface (which would be a pretty significant duplication problem in a larger domain)? If so, how do they map to the existing ones?
Typically when you use the designer the flow is the opposite - you create the model with the designer (or create/update the model from the database) and then the code is created for you. The created code can be either the EF1 style code with entities derived from EntityObject and attributes etc. which is created with a Single File Generator which is a part of VS (Code Generation Strategy set to "Default") or the code can be created with T4 templates (Code Generation Strategy set to "None") in which case you need to add T4 templates to your project. EF matches POCOs with Entities from the edmx file by convention (names of entities have to be the same, names and types of properties have to match etc.). In the article for some reason they went the opposite way which is weird since it requires that you create all the entities and relationships with the designer manually (since the designer does not know how to create entities from the code) and make sure that the requirements for the conventions (you may not even be aware of some of them) are met. However when you start with code the better approach is to use the EF Code First approach and skip the designer entirely. Code First can create database from your code. It also contains migrations feature which allows evolving your database along with your code. Finally (as you seem to use Visual Studio 2010) you could use EF6 which allows using all the goodness that was previously only available on .NET Framework 4.5 to be used on .NET Framework 4. See here for more details: http://entityframework.codeplex.com/
*the names are going to change in the new version designer that supports EF6 and works with Visual Studio 2012 and Visual Studio 2013
EDIT to address questions from the comment
If you would like to use Code First would use the DbContext API which is a streamlined wrapper of the ObjectContext API. Here is a walkthrough that should help get you started.
You can still use Code First if you have an existing database - the difference is that you will not be able to use migrations. The easiest way to get started with this is to use EF Power Tools. Take a look at this tutorial to see how to do that.
More help here

Defining business objects in Entity Framework

Trying to understand Entity Framework. My approach is database first. However I would like to define other entites in the model that is closer to my business objects. I guess I could write queries in the db and include them in the model. But I would also like to define entirely new entities in the model though they would be based on underlying tables in the db. How do I do that - does anyone know a tutorial?
Regards
Bjørn
db Oldtimer, EF Newbie
Database first means that you have existing database and you can either create model by updating from database or manually. You can use wizard to create initial model and modify it manually to define new entities but you must not use update from database any more or some of your changes will be deleted. Also your custom modifications must follow EF mapping rules (for example it is not directly possible to map multiple entities to the same table except some more advanced mapping scenarios like splitting and inheritance) and some of them (custom queries) must be done directly in EDMX source (XML) because designer doesn't support them - this requires more complex knowledge of EF mapping and it will be definitely hard for newbie.
You can check specification of that XML. For entities mapped to custom queries you will have to use DefiningQuery element in SSDL part of EDMX.

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.