Ignore a specific column in Entity Framework? [duplicate] - c#

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.

Related

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

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?

Get Number of Entities and its Fields Programmaticaly, Data-driven Application

I want to create a dynamic datadriven application for practice purposes.
If I have a Modell with a Entity and I need a new one, then I want to create it only in the Diagram (modell) and thats all.
Everything else should be done dynamically, adding the new entity to b.e a Listbox, make it clickable and create a "Show Datas" and a "New/Edit" Tab with the right labels and textboxes in it. (For editing/creating new)
What I would like to know is, how can I:
Get the number of the entities
Is it possible to update the database, without needing to delete it and create new (Else I would loose all Data), if hopefully yes, how?
Get all the fields from a Entity? (Do I must work here with Reflection?)
Hope someone could help
1.Get the number of the entities
Using Context object you get the list of entities. there you can use the .Count() to check the no of entities of that type.
2.Is it possible to update the database, without needing to delete it and create new (Else I would loose all Data), if hopefully yes, how?
This question is little unclear. you want to delete database.. or entity?? you can do any operation on entities that will be reflected on back end if you want. Regarding database delete and create operation, entity framework is not designed for.
Yes you can add new entity to model and then map it with the back end tables.. it is possible to modify the model as per your backend. Even you can create you custom entites that reflect operation on multiple tables on the database but with some care about data integration.
3.Get all the fields from a Entity? (Do I must work here with Reflection?)
Yes.. To access the properties of Entity with out knowing their name you should go through reflection.

LINQ to SQL - entity properties - overwriting one entity with another

First, a little background. I have a DataContext object (Linq to SQL). I use this to interact with my SQL database. I'm using C# in Visual Studio 2010.
The problem is this: I can edit an entry from an entity table that I want. I select the entity with a query, change the particular field, then submit the data context changes. But let's say that I get a separate entity. This entity is actually an edited version of one of the existing entities. So what wants to happen is for this one to overwrite that one. Now, yes, this is possible. You check the primary key, and overwrite the fields from the old one with the fields of the new one. So where's the problem? The problem is if the entity has 40+ fields, it's a pain to assign each field individually. Is there no method or way of doing this more quickly?
Thanks.
You can use the Attach() method. If an entity with the same ID already exists in the database, it will be overwrirtten with the attached entity.
myDataContext.Customers.Attach(myCustomer);
myDataContext.SubmitChanges();
You can use Automapper framework for that purpose. Also it can be used for multiple routine needs as mapping for example

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.

How to relate Linq-To-Sql objects that are on different dbml diagrams?

I have two different dbml diagrams reflecting my Linq-To-SQL classes. (This is necessary, because they appear in different projects.) One of the objects in the one diagram needs an association with an object in the other diagram.
How do I do it?
Actually your two diagrams meens two different data contexts will be generated. I also guess your using SqlMetal on the diagrams to generate your entities.
You will need to include all associated objects in one diagram or the datacontext wont be able to retrieve that relationship from the database for you.
Another option is using custom entities and an XML mapping file.
I had a concern about this issue myself, which is why in my case, I put all the entities in one context. The context is too big and complex to use in the designer now (it takes about 20 minutes to load and probably has more than 100 entities), so we use SQLMetal (the command line form of the DBML compiler/generator) to build it instead. The DBML itself is maintained with (generated by) a tool I created for designing our schema. It's not exactly an answer to your question, but is one way to deal with this concern.
As it turns out, the easiest way I found to accomplish this is by forcing the relationship. I created my own partial class to match the class containing the FK, and just mimicked the generated code that I found for other relationships.
This has only one shortcoming AFAI can tell: there's a piece of generated code in the actual foreign key field's set property that should throw an exception if you try and set the value when there's already a value in place:
if (this._Parent.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
But I'm prepared to live without that, as long as I know that I shouldn't be setting the FK field explicitly.

Categories