Override edmx model generation from database - c#

When using EF Database First, it's easy to select tables/sprocs from the database, and have these added to the model.
However I want to customize the way the model is updated from the database, to automatically set certain features, and save user effort/error.
To be clear, I'm not talking about making changes at the point of the tt file generation, but actually when the edmx is populated from the database via the wizard.
The particular actions I'm interested in are:
Automatically adding some sprocs to the model when a table is added, based on a strict convention.
Setting those sprocs to be Private (they are Public by default)
Automatically mapping those sprocs to the CRUD operations for the table.
It seems that there are a couple of options:
Override the default model generation, so that the changes are made when the table is added/updated.
Update the XML for the edmx after tables are added (can I trigger this automatically?)
I'd rather do option 1, as it would be far cleaner, but haven't found a mechanism to achieve this yet. (I'm working through the EF code from CodePlex at the moment!)
Am I stuck with option 2?

Related

How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?

Assumptions
Using EF 6.1, MVC 5, VS 2013, C#
I have an existing database model designed in Toad DM for SQL Server and it's very important keep it always updated
Steps and Notes
Using ADO.NET Entity Data Model I chose Code First from Database (new feature in EF 6.1) to generate the models. Note: Model classes and DbContext class generated successfuly but NO .edmx or .tt file was generated.
Next I added a new scaffold item: MVC 5 Controllers with views, using Entity Framework. Note: Success, controllers and views generated
Question
From now on I don't want to use Code First to update my database. Instead I want the models to be updated based on database changes. What to do next? If I don't have an edmx file will I not be able to update my model classes from the database?
The Entity Data Model Wizard's Code First from Database does an excellent job creating your entity classes, as if they were created in the Code First style. What you are asking is if there is any way to keep these classes up-to-date as your database changes, similar to the EDMX style "Update Model From Database". From what I've researched this is not possible using the built-in tooling. However, here is one workaround that I've found useful:
Let's say I have database with a product table and customer table. Originally I created a StoreDBContext class, and selected product as one of my objects. Now I want to add the customer table as a new entity to the existing context. Here's how to do this using the Code First Wizard:
Create a new Entity Data Model, call it StoreDBContextTemp or whatever
Choose the code first from database wizard option
Select customer as an object to add (just customer) & complete the wizard
Open the newly created context file, StoreDBContextTemp.cs, and copy the virtual properties of your newly added entities:
public virtual DbSet<Customer> Customers {get; set;}
Paste these new properties into your Original StoreDBContext.cs dbcontext class.
Delete StoreDBContextTemp.cs, and remove the connection string for StoreDBContextTemp in app.config/web.confg etc.
You can now use Customer on the StoreDBContext class
If you add or remove tables you will need to manually adjust fields, but at least you won't need to hand write dozens of properties each time a new table is added to the model.
One more option is just delete the auto generated classes from the project and once again generate them.
While following this approach only thing we need to make sure that is we should give the same name for the data model(class name which inherits from DbContext ) as the previous one.Data model name is highlighted in below snap
Three things.
There's no .edmx when you use Code First.
If you use Code First Migrations you would have to write first the code and after that migrate the changes to database. This helps you to have much more organized you code with no generated code which is an advantage.
There's a plugin in Visual Studio for doing contrary. Entity Framework PowerTools allows you to select the database and map it to objects.
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
The best solution to me is deleting the model and recreate updated one with the same name, keeping in mind two points:
Personal extension methods implemented for the model;
Possible manual relationships between tables added to the model because of not setted up in the phisical db.
My personal solution:
Move all extension methods to another partial class that won't be overrided;
Insert all added properties of an entity to another partial class;
Keep track of all manual relationships in an help file, so you can add them again being sure not to loose anything;
Delete the old model and recreate one new with the same name and update it with the manual relationships of point 3.

"Update Model from Database" wizard is deleting mappings of renamed POCO classes

I'm building an application using EF 5 to talk to an existing Oracle database. I'm not allowed to change any part of the DB schema. I have generated my model from the database using the VS2012 wizard, and all classes are named after their Oracle counterparts.
The naming of objects in the database is QUITE_UGLY_AND_INCONSISTENT, so I'd like to rename the POCO classes and properties. I can easily do that from the EDM Designer. As a result, I get neatly named class and property names, that are mapped to the UGLY_NAMED tables from the DB. I can successfully perform queries and everything works smoothly. Exactly what I wanted.
However, when I need to add new tables to the model, I run the "Update Model from Database" wizard and check the additional tables to import. It suddenly lists my renamed (but still correctly mapped) classes under the Delete tab, saying it can't find them in the database. When I click Finish, my existing classes are unmapped and I have to manually re-map each property to its corresponding DB column... Or roll back to the previous version of the EDMX file from version control.
I'm looking for what you think would be the most elegant solution to this problem, since I need the application to be as maintainable as possible. I strongly favour an approach that lets me auto-generate new classes from the database while preserving the existing renamed objects and their mappings.
Am I overlooking some way to prevent the Update Model wizard from deleting my existing mappings?
Should I use a different approach to renaming the generated classes?
Should I leave the generated classes unchanged and instead construct sanely-named wrapper classes that are exposed to the rest of my application?
Should I refrain from auto-generation and instead go for a code-first approach? This is a very unfavorable option, because I need the time spent on manual model coding and mapping to be as little as possible. Adding objects will be a very frequent task.
Should I perhaps even use a different ORM altogether..?
I discovered the culprit myself: running the "Generate Database from Model" wizard due to a recommendation in an article I read somewhere. It changed all the model's underlying table and column names to SQL Server standard names ([dbo].[Customers].[CustomerID] etc.).

Can Entity Framework 4.1 designer "update model from database" for selected entities only?

The situation: Sometimes a database schema is not what you would consider an ideal representation of the system's information and you may not be able to change it. We have been using Entity Framework to create a nicer conceptual model to code against in situations like this. This means updating the model from the database and then changing it ourselves, either through the designer or through the .edmx file directly using a text editor.
The problem: When you update the model from the database, all your carefully made changes are thrown out the window. This can make adding new entities a real hassle as you are basically forced to do it through editing the .edmx file directly.
The question: Is there a way to get the Entity Framework to only update selected entities from from the database? Or is it possible to tell it to leave the rest of the model alone when adding a new entity?
Thanks!
No there is no way to make selective updates with built-in designer. Also the designer doesn't throw away all your changes. It usually doesn't touch conceptual model (except some rare occasions where it continuously renames some associations) and mapping but it always deletes storage model and override it with new definition. I worked without any problem with modifications to my conceptual model and mapping and running updates from the database.
Designer works as any other in Visual Studio - touching the generated code (storage model) is not supported feature. Once you do it you cannot use Update from database anymore.
There is commercial tool which probably supports better model updating - you can try a trial.
If by updating selected entities, you mean just one or more tables, you can delete those tables from the model, and then add them back in individually to pull in changes tables by choosing them individually - I do that often as underlying tables are changed (especially during development).
You do end up losing any manual changes you made to those re-added entities after the entity/table was pulled into the model (i.e. I often rename my navigation properties and then after each re-import of the table I need to manually rename them again).

Keep Database Content On Model Change

Using the code-first approach available in the new 4.1 RC.
Is there any way to persist the current data stored in a database when the mode changes? The database is created by the entity framework, and usually the database is dropped and recreated on model changes.
Obviously as soon as the model is changed it will not be possible to use the context object to connect to the database to retrieve the data, so what are the options?
Code first doesn't support database migration / evolution yet. If you want to do incremental DB development use model first (EDMX) with DbContext Generator T4 template and Entity designer database generation pack which is able to create diff. scripts from the model.
From Scott Gu:
Importantly, though, the auto-create
database option is just an option – it
is definitely not required. If you
point your connection-string at an
existing database then EF “code first”
will not try and create one
automatically. The auto-recreate
option also won’t be enabled unless
you explicitly want EF to do this – so
you don’t need to worry about it
dropping and recreating your database
unless you’ve explicitly indicated you
want it to do so.

EF4 Custom Entities within the same edmx

I have an edmx file that reflects 100% my DB schema.
Along with this I need to create some custom Entities based on the existent, pretty much like a view that will aggregate fields of several entites into a single one.
The problem is that this isn't quite working. I tried several approaches but it always gave me conflicts with the actual entites already on the edmx.
I need to have those entities that reflect my DB schema, so do I have to create another edmx file to hold my custom entites and avoid colisions?
I also though of:
create a stored procedure but then if
I need to filter the SP result I
eather have to add support for serach
on the SP of get all the rows and
filter with Linq2Objects... won't do
this!
create a View, and this one would
work pretty well but I want to try
to do this making use of the EF4
designer and keep everything in one
place.
Could anyone point me to some examples?
I think what you are describing is a view so this is probably the right way to go.
You can store the view code in the edmx using the DefiningQuery node. You don't need to create the view in the database. However there is no designer support for this feature, you will need to hand edit the edmx. The changes you make should be persisted if you refresh the edmx from the database using the designer.
Details here:
http://msdn.microsoft.com/en-us/library/cc982038.aspx
http://blogs.msdn.com/b/davidebb/archive/2010/10/01/the-easy-way-to-create-an-entity-framework-defining-query.aspx
It would be easier just to create the views in the database, and let the designer find and model them.
This entity will be read-only, but of course you can then assign SPs for UPDATE/INSERT/DELETE if you want to support modifications via this view.
You can't define two entities based on same table except special cases (table splitting, hiearchy mapping). In this case you have to use DefiningQuery as #James suggested or QueryView. The difference is that DefiningQuery is defined in storage model and it is common SQL. QueryView is defined in conceptual model and it is ESQL defined on top of already existing entities. QueryView supports only some features of ESQL (for example it doesn't support aggregate functions). In both cases you have to modify EDMX directly (XML), these features are not supported in designer.
Database view mentioned by #James is also an option if you don't want to use these advanced EF features. You can as well simply expose predefined queries on your object context and map return projection to custom type.
Be aware that neither of these methods will allow you to modify, insert or delete data.

Categories