How to Exclude Certain Columns in EF6 Using Database First? [duplicate] - c#

This question already has answers here:
Entity Framework: Ignore Columns
(7 answers)
How do you update an edmx file with database changes?
(6 answers)
Closed 6 years ago.
I am working on a project which has a fairly complex database, and the code is stop-gap while another system overhaul is underway.
I am fixing up some legacy code, and need to perform work quickly and use work-arounds wherever possible.
There is an existing database and I am using EF6 Datbase First with much success.
However, I am discovering various cases (up to my 4th one now) where a particular column is not needed in my code, and EF is tripping up on type conversion issues.
I have found the fast solution (and preferred by my client) is to simply remove these columns from the EF model - which I have been doing manually after "update from database" - which I must do each time I fix a view or table, etc.
Is there a way I can somehow instruct EF "Update from Datbase" operation to ignore certain columns?
I have seen this for Code First - where OnModelCreating can be overridden to set an ignore property - or where a similar attribute is added to the existing property to inform EF when to ignore certain properties.
I had thought about using a partial class - defined in a .cs file in a subfolder where I could put some code to cause this to happen - however I can not annotate the property - as it would be defined twice - once in my partial, and one in the .cs generated by the T4 template.
I've been searching online for a technique to manage this, and I have not found anything.
For example:
Database has Table X, Column1, Column2, Column3.
Update from Database will create entity model for Table X, with all 3 columns.
After Update From Database, I can removed "Column2" reference, and all is well - there is no Column2 property on the model class, and my code simply never references any data in Column2.
What I am seeking is something I can put somewhere - in the database, the EF model, or partial class that will not be over-written each time I do an Update from Database.
Any suggestions?

Related

Incremental ETL on code first many-to-many association table

I'm setting up a data warehouse (in SQL Server) together with our engineers we got almost everything up and running. Our main application also uses SQL Server as backend, and aims to be code first while using the entity framework. In most tables we added a column like updatedAt to allow for incremental loading to our data warehouse, but there is a many-to-many association table created by the entity framework which we cannot modify. The table consists of two GUID columns with a composite key, so they are not iterable like an incrementing integer or dates. We are now basically figuring out the options on how to enable incremental load on this table, but there is little information to be found.
After searching for a while I mostly came across posts which explained how it's not possible to manually add columns (such as updatedAt) to the association table, such as here Create code first, many to many, with additional fields in association table. Suggestions are to split out the table into two one-to-many tables. We would like to prevent this if possible.
Another potential option would be to turn on change data capture on the server, but that would potentially defeat the purpose of code first in the application.
Another thought was to add a column in the database itself, not in code, with a default value of the current datetime. But that might also be impossible / non compatible with the entity framework, as well as defeating the code first principle.
Are we missing anything? Are there other solutions for this? The ideal solution would be a code first solution, or a solution in the ETL process without affecting the base application, without changing too much. Any suggestions are appreciated.

Entity framework edmx fail to Update. Error appear "An entry with same key already exists." [duplicate]

This question already has answers here:
Error modifying DAL, System.ArgumentException, "An entry with the same key already exist"
(7 answers)
Closed 6 years ago.
I am trying to update my edmx, RIGHT CLICK -> UPDATE MODEL FROM DATABASE. And each time i try to update error appear "An entry with the same key already exists
Can some buddy please help?
."
Sometimes the duplicate might not be shown in the edmx diagram, it could the code side. EF can get a little messy sometimes but not too good in dealing with those loop holes.
As an addition to Fernanda's suggestion, the cleanest way is to delete your edmx file and reconfigure the connection string again.
in case you don't want to do that, you can delete all tables & functions in your edmx, save it and see if the same error still occur. If the same error don't occur anymore, re-add everything and save it.
Note that EDMX approach will be deprecated in Entity Framework 7:
“Update model from database” is a process that allows you to
incrementally pull additional database objects (or changes to existing
database objects) into your EDMX model. Unfortunately the
implementation of this feature wasn’t great and you would often end up
losing customizations you had made to the model, or having to manually
fix-up some of the changes the wizard tried to apply (often dropping
to hand editing the xml).
For Code First you can re-run the reverse engineer process and have it
regenerate your model. This works fine in basic scenarios, but you
have to be careful how you customize the model otherwise your changes
will get reverted when the code is re-generated. There are some
customizations that are difficult to apply without editing the
scaffolded code.
So the recommended approach for EF 7 is to do reverse engineering of database into code, not into edmx, something called code second approach before.

Ignore a specific column in Entity Framework? [duplicate]

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.

"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 I map arbitrary SQL queries to Entity Framework fields?

Is it possible to add fields to an entity framework class that rather than being mapped to a column in a table instead map to a SQL query?
For a contrived example (NB: This is not what I'm actually trying to do just an easier to explain example of what I'm trying to accomplish) I want my class to have a TableCount field that holds the result of SELECT COUNT(*) FROM MyTable at the time the object was loaded from the db.
EDIT: I should have mentioned this in my original post but I'm using POCO classes.
You cannot do it directly with entity mapped to a database but there are two ways how to achieve it with a new entity type containing columns from your original entity and your additional computed columns:
Create database view and map that view - this is fully automatic way maintained by EDMX designer for you
Write query to populate whole new entity type and map it manually in DefiningQuery. The disadvantage is that it requires manual EDMX editing and without additional (commercial) tool also manual maintenance of EDMX because standard VS EDMX Designer overwrites edited SSDL part every time you select update from database.

Categories