In order to populate Dropdownlists, showing the details rather than id on Gridviews (showing City name instead of Birt city id), etc., sometimes we need to retrieve data at the same time from Master (for ex. Student) and Detail (for ex. City) tables. Could you suggest me which scenarios below is the most suitable? In addition to this I would be appreciated if you suggest other approaches provided that using Entity Framework.
1) I retrieve data from Entity tables and I use relations between master and detail tables. But in that case I need to define these relations on my DbContext and I have to populate dropdownlists by methods. But for displaying data I need to define another methods or etc. For this reason actually I do not like this approach. What do you think for this?
2) Instead of this I can use ModelView as I had used before. But, I think it is not good idea return more tables instead of one table lots of times. In addition to this, I think I need a extra definition for dropdownlist for example in an htl helper. I think it is also not handy.
3) As it is used commonly, I think getting data from entity views (database view) instead of entity table seems to be very useful. With the help of this approach, I can retrieve data from 2 tables and I can easily show this data on dropdownlists and grids without an extra effort. What do you think?
a) On the other hand, if I use a view entity instead of table entity, how can I save this entity to the database (normally I return table entity for creating/editing).
b) If this method is good, in that case I think I need extra entity definitions for the related database views in addition to the tables. For example I have Student, City entities now. But for the database View I need another 3rd entity. Could you give me a usage example for this approach?
BR.
Related
I am working on an Angular (v6) project on ASP.NET MVC for backend and Entity Framework. Sometimes a have some CRUD operations that updates only 2-3 fields on an entity and in this situation I may be confused about which approach would be better for best practices for this scenario. As an example, let's say I have a Employee entity with the following properties shown below:
Employee: Id, Status, Name, Surname, Job, Department, HireDate, BirthDate, Address, Updated...
Assuming update for Status, Department and Updated field, I can perform this for the following approaches:
Approach I:
I can create an instance of employee.ts file and fill it in component.ts by only the fields to be updated and then pass it to service.ts and pass to the Controller.cs. In the Controller I receive the model as Employee entity model and set Updated field in the Controller and pass this Employee entity to the Service.cs and then save this entity using the related EF methods.
Approach II:
I just send Id, Status and Department values from Component.ts to service.ts and then pass to the Controller as int values (Id's). Then in the controller create a new instance of the Employee.cs entity and fill these 3 fields and Updated field. Then pass this entity to the Service.cs and then save this entity using the related EF methods.
Approach III:
Same as approach II until Controller.cs. Then pass these 3 parameters to the Service ts and then retrieve the Employee from database via the Id parameter. Then set the other fields and save the entity.
I think 3 of them can be used but not sure which one is better for this scenario in Angular projects with EF? Any help would be appreciated...
Approach 3, or
Approach 4:
Create an UpdateEmployeeViewModel with the PK & fields you want to update to populate in your TS, pass to the controller which validates the data, loads the entity, transfers the appropriate values and saves. When it's one or two columns then Approach 3 is fine. If it grows to more than that then I typically opt for #4.
I would avoid approach 1 at all costs. It is too convenient to have code trust the entity passed from the client. The call to your service can be intercepted and adjusted so if you server code accepts an entity you may easily find code that does a DbSet.Update or DbSet.Attach which could result in tampered data being persisted to the database.
Approach 2 also leaves issues when performing updates as an entity should always reflect its data row. Creating an entity and only partially filling it then attempting to update the data state could result in unintentional updates such as clearing out values. Down the road you may have other common methods that would accept an entity as a parameter but you have cases where the passed entity may be complete (loaded from DB) vs. incomplete (constructed by an update method)
Loading an entity by ID is quite fast so there is rarely a need to over-optimize. It also can help to check the row version # to ensure that the version of the entity you are updating matches the version still in the DB. (Did someone else update this row since you initially sent it to the client?)
I have tables with the same structure but with a letter prefix of every table.
For example:
A_Company, B_Company, C_Company
There is combo box from which the user can select A, B or C, and then the code saves data into the appropriate table.
How can I do this using EF database-first?
I solved this problem adding a column for code prefix and triggers on my base table company for insert update and delete.
As the other commenters have said, it would be much better to refactor the database to a single table. If you can't do that then the only other thing that I can think of is to have a class which will select the table for you.
I would create a new class which has the same properties as your company tables, and also has the descriminator property. This would then be used as the data source for your ui.
in this class you would have to code manually to draw the data from the correct actual table (and save to it) based on the value of the discriminator. This is fine if you have only a few tables, but as your number of identical tables grows large, this will become more of a headache.
It might be possible to have the base tables all inherit from a virtual base class which would help a bit - you could then create a dictionary which the base class could use to switch the final data source on the fly.
As a final thought have you considered:
1. Creating the master table as suggested by the other commentators as a single table and then having views for each company.
Creating the master table as suggested and then having code to create the individual tables from that one at some point prior to their use?
I'm trying to model a database currently using EntityFramework's Fluent Configuration. I cannot edit or otherwise control the database schema. The entity I am trying to model has a lot of look-up tables - for example, one property (it's name) has a whole table devoted to it with a name associated with an id (which is it's language). In other words, it looks a bit like this in the database:
Entity
string[] Names
Entity_Names
string Name
int LanguageId // 9 = English
However, I am trying to condense this into
Entity
string Name // I only want the English name
Using a SQL query, this would be pretty simple - but how can I do this via Entity Framework's fluent configurations? There are a lot more of these instances as well, but this is the simplest example I could come up with.
If you do manage to flatten the model this way, it's almost certainly going to be a read-only view of the data. There's no way for Entity Framework to know that a string property should be looked up in another table and replaced with an integer id.
So that leaves two options if you're okay with it being view-only. Write a database view that replaces the ids with the strings and build an entity for that view.
Or build entities that are compatible with the schema model and project the data into a dto.
The second approach is the one I'd prefer as it means you'd still have a compatible entity model if you do need to CRUD.
I have a class, suppose it's called EntityModel, and I want to make three different tables with the same columns, as defined in EntityModel. Let's call the tables tbPast, tbPresent and tbFuture. I want also to access them separetely in the Entity DbContext:
using (var db = new MyContext())
{
var element = db.Past.Find(id);
db.Past.Remove(element);
db.Present.Add(element);
db.SaveChanges();
}
The main purpose of having three tables is performance: the table will have millions of rows, and the most important is the Present, with dozens of rows. Most queries will be made in the Present table.
What is the best way to do this? Implementing three models with the same properties doesn't seem right for me.
I'm using Entity Framework, with the Code First approach, along with ASP.NET MVC 3.
You can't use the same model to generate separate tables w/ EF code-first. If you need to have some sort of grouping, use a Discriminator field and assing it any of the values: Past Present Future.
Edit:
Similar effect can be achieved through table-per-concrete type inheritance. Thus each type will have it's own table and can share most (if not all) of the fields.
I think this is a question of the best technique or best way to skin a cat!
Imagine a menu with items (menu choices) on it. I have a table called MenuItem, which for example "Spaghetti Bolognese", it has lots of other information associated with it aside from just a better description and picture.
Eg.
Basic Information (Name, Description, Picture, etc)
Nutritional Information (approx 15 columns)
Allergy Information (approx 16 columns)
Dietary Information (another 7 columns) (religious etc)
As it is at the moment I have it all in the one table in SQL server, which is logical database design to me as it doesn't repeat, despite it making the field list for the table longer than I would like. I'd already been feeling a bit bad about just continually extending the database table. But now we also want to add 'Recipe' information, approx another 7 columns.
I'm using Entity Framework 4.latest, and feel there is probably functionality to help me split this off within the EDMX? (Is that what ComplexTypes are?) Or do I just need to do this in the ViewModel class I call?
I think what I'm after using in my code to segregate things better is something like
MenuItem.Recipe.Ingredients
MenuItem.Nutrition.Fat
etc
Complex types can help you but be aware that complex types cannot contain navigation properties, cannot be null and are always loaded with the entity. Other possibility is to use table splitting - this will allow you to map multiple one-to-one related entities to the same table. The main features of table splitting are:
Entities can share only primary key properties
There is one main entity and others are considered as relations (navigation properties)
Related entities must exists - they are not optional so when you insert new main entity you must insert these related entities as well even if they are empty
Related entities must be loaded with eager, lazy or explicit loading