I am use EF6, the database-first, i.e. with the creation of an EDMX model. One table is used by previous developers to store different entities. It's very wrong and it causes trouble.
The task is to leave the existing code as is and try to create different classes from this table. It seems to me the most logical to create several Views based on this table, each of which would represent the required class. You can write insert, update, delete to such View, since it refers to one table. The problem is that when you try to update an object created from the View, an error occurs.
System.Data.Entity.Infrastructure.DbUpdateException: "Unable to update the EntitySet 'Sample' because it has a DefiningQuery and no element exists in the element to support the current operation."
The entity understands that this is a view and, in general, cannot be updated.
So far, I see 2 ways to solve the problem:
Create Update, Insert, Delete function manually.
Manually configure the View data through the Fluent API (if possible).
I like the second option better. The problem is that the Fluent Api is more of a code-first approach. I can't get the OnModelCreating (DbModelBuilder modelBuilder) method to be called.
Is it possible to use EDMX model and Fluent Api together?
What other solutions can you suggest?
Related
I have a database with some tables for school related project and I have a model with EF 6.0 SQL-first approach. I need to update the database with a new table & update an existing table with a new column. The twist is: I don’t have any *.edmx file.
How can I update the model without it? If it is impossible, then how can I generate *.edmx without interrupting the existing model?
Entities are essentially POCOs, so you really just need to update your schema and update the entity classes to match. For new entities if the project is not using an edmx then it should either be using classes extending EntityTypeConfiguration or setting things up with the modelBuilder on the OnModelCreating event in the DbContext.
EF can resolve most general mappings using convention, so adding a column to a table usually just means adding the property to the entity. Mapping only comes into play when you want to change a columns naming, handle type casting differences, or use identity/computed columns. For new entities it can also use convention, but commonly there would be config used for the Table name, PK name, and things like Identity columns, plus navigation properties for related entities.
This question already has answers here:
Entity Framework: Ignore Columns
(7 answers)
Closed 9 years ago.
I have auto generated model from a database in Entity Framework version 4.1.10331.0.
I want to ignore a column from an entity without using the Fluent Api and without changing the ObjectContext into DbContext (and of course without deleting the column from the SQL table) and without marking the property generated in the model with the attribute NotMapped, because whenever I update my context in the model that column will reappear.
Can someone please help me in this case?
Thanks and best regards Ben
I don't see the problem updating your EF each time you regenerate the model, but I can propose 2 solutions:
Create a View that contains the columns you need, then generated it in EF.
Create another class derived from you entity that will show the data you want. This class will be your "application Entity" (As you know additional management should be considered here)
EF database-first is very under-tooled in many places. Similarily to your problem, if you generate a model from DB and rename a column in CodeSpace (so column users.col_chr_UsrName is just User.Name), you also would lose it when regenerating the model.
If I remember well, in EF3, EF4 and even in EF5 there is no way to preserve them. If you just "update" the model, they have a chance of surviving, but regenerating never preserves anything.
You can try to create a script or set of scripts that you will run after regenerating, and those scripts may seek and apply fixes to the generated model. But thats, well, "workaround" (literally, work and around), not a real solution.
Another thing, with more work, is to define Views or StoredProcedures (or custom table mappings) that will handle the projection, but they sometimes also may get hairy after regenerating (especially custom table maping which will always evaporate).
You can actually ignore the unwanted columns and prepare a set of light LINQ wrappers/accessors that will perform the projection, and put them in some static MyTables class and use that class instead of RawTable. That will work and may be usable, but is not again pretty.
IMHO, the best approach is to use either a script that will fix the model afterwards, or live with the unwanted columns, or .. not use the autogeneration from within the designer. Try to find another, more smart, generator.
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).
I need to use an 'DropCreateDatabaseIfModelChanges' - Initializer class, because I want to create one special entity (table), if it doesn't exist. My problem is, that I've also got another entity in my DbContext, which shouldn't be part of the model compatibility check.
I'm getting the following error message:
Model compatibility cannot be checked because the EdmMetadata type was not inclu
ded in the model. Ensure that IncludeMetadataConvention has been added to the Db
ModelBuilder conventions.
Is there any possibility to exclude a special entity from this check?
EDIT:
I've done what Devart has suggested. The problem seems to be different, than I first tought. It all works fine, if I let EF create a new database with my CheckedContext. But I'm getting the error message above, when I'll try to use my NonCheckedContext wich should use an existing table ...
EDIT2:
This is a working solution. Everything works fine, when the database doesn't exist before. But it's no option for me, to Drop/Create the database.
A possible solution: create a context class inherited from DbContext, and then create two separate subcontexts inherited from the base one - CheckedContext and NonCheckedContext, and set the Database Initialization Strategy accordingly.
Please note that you should access the CheckedContext first so that it fires all its checks.
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.