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

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.

Related

How to make it explicit in Web API 2 for Entity Framework to only add parts of the object that have changed?

I'm using ASP.NET WebApi 2 and loading in part of a relational database structure into the front end website. This allows the user to make changes to multiple tables in a single store and to also view some extra data.
This mostly works pretty well. It means I can store changes to, say a person table and their related clothes and hair color on one call as follows:
db.person.Add(person);
db.SaveChanges();
The problem is that, I don't want to load all the related data. So where the shoe table may be loaded, I don't want the laces table to load with info about laces.
The issue I'm running into is that there is an attempt to store a duplicate shoe table to the database even though this was only loaded to allow the user to view these details. I imagine that this is because, I'm using [JsonIgnore] attributes to ignore certain parts of the object - it is thus recognizing this as a new object, when it isn't.
I could loop through the object removing any shoe information before call Add, but this would be slow.
Perhaps it is best to post a second object that only includes the items that have changed (after tracking these in the front end). Is there a better way?
When you use DbSet<T>.Add() in EF, the entity (or all the entitis in the tree, if it's an entity with related child entities) is attached to the DbContext as Added. That means that when you call SaveChanges EF will try to insert all the objects in the database. That's why you're getting duplication problems.
You need to learn how to work in disconnected mode with EF. Basically you need to track the state of each entity (i.e. control if they have to be inserted, deleted or updated), and set the correct state when you attach the entities in the context.
Look for docs on working with disconnected entities in EF, for example:
Persistence in Entity Framework
Add, Attach and Entity States
These will explain you how to handle disconnected entities.

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.

What to use with a half-designed database? Model-First or Database-First?

Let's say you have a database that is currently in use. It has one table that contains some information about Customers.
And let's say that you want to create an application around it. You need to use the Customers table in your program, but you also need to add some new tables, possibly connected to the Customers. For example, you need to add an Orders table that has some association to the Customers table.
I have started to learn Entity Framework. I have learned a bit about "Database-First" and "Model-First" data models. But the situation is, what I want to do doesn't fit into any of these categories. I neither have a completely empty database, nor a finished database schema that can directly be used in the program.
What should I do? If I go with "Model-First" and design my entities using the Visual Studio Designer, can I just use it to create the relevant part of the database schema?
Go with Data-first, THEN go with Model-first. You don't have to pick... use the data-first wizard to generate EF for your existing table, then use the designers to create additional objects, then sync that back to your database. The concepts of model-first and data-first only applies to the initial creating of your EF stuff - anything you do after that can by synced in either direction.
This shows how to put database changes back into your model after it's created - you can do the other way too, but I can't find that article - all the new videos and crap are hard to navigate - you may be able to find it.
http://msdn.microsoft.com/en-us/data/jj206878
After all, the framework wouldn't be very useful if it locked you into never being able to update anything. Right?
The more development into your project, the more Database-First it'll become, so I suggest you to go with Database-First right now and then extent your EF entities and then implement/fake/mock the missing pieces
If you haven't read about TDD, it's time to do so now. It'll save a ton of time down the road especially when working with an ever changing data model.

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.

Categories