I'm rather new to software development and I am very confused as what classes in the model should represent, i will elaborate a scenario and i will ask a couple questions at the end. I'm using VS 2013 with MVC.
I have 3 tables,
tblStudent (*StudentID, StudentName, StudentLastName, StudentDateOfBirth)
tblModule (*ModuleID, ModuleName, ModuleDescription)
tblStudentModules (*StudentID, *ModuleID) - table created to break many to many relationships
And i want to execute this query using a stored procedure in the database:
SELECT A.StudentID
,A.StudentName]
,A.StudentLastName
,B.ModuleName
FROM tblStudent A, tblModule B, tblStudentModules C
Where A.StudentID = C.StudentID
And B.ModuleID = C.ModuleID
Now, my query uses 3 tables, and the result is a combination of different attributes of the tables i have, so should my model classes represent individual objects (i.e Student, modules ) or should they represent the result set of the Query that i want to execute (a class with StudentID, StudentName ,StudentLastName, ModuleName) so I can map the result of the stored procedure to a single model class?
Models are the business layer when considering MVC applications. It will be created based on database structure. Always create models for the tables of your database.
That is, you should need to create models for tblStudent , tblModule and tblStudentModules .
ViewModel is one of the unspoken layer in the Asp.Net MVC application. It fits between Model and View and act as a data container for View. ViewModel is View specific data. It will be created based on the View. So, you need to create viewmodels based on every view. These viewmodels may or may not contain variables of the original models.
That is, you need to create a viewmodel for the stored procedure you are writing which contains StudentID, StudentName, StudentLastName and ModuleName. That is, what all things we need to display in a view page are the variables of the viewmodel.
View is going to be a strongly typed view of type ViewModel.
Model and ViewModel should be independent of each other. Controller
will create and initialises ViewModel object based on one or more
Model object.
Personal opinion - but a class in a model as described above should represent a 'thing', be it a Student, a Module, or a Relationship between the two.
If you were to use Entity Framework for example to interact with the database from code then this is how the database would be represented, a collection of three classes, one for each of the tables you have described.
This is a very complex subject that can't have a quick answer however the cut down version is:
Don't confuse the database model with the object model, while there are many point of similarity they are not the same thing.
An Object is a Entity that contains naturally grouped items and functions
Where as a Table is normalised representation of data
To use your example you have Students and Modules that are primary entities that uses a 3rd table to maintain a relationship
On the object model you would have a Student class, and a Module class
the Student class would have a collection of modules inside it. so the student will manage its own relationships with modules and each module may contain a collection of student allowing it to maintain its relationship as well.
However a Student is a Type of Person so you might define a Person class and then have student Inherit from this class and expand its functionality to include student behaviour, now in this situation a person would probably not have any meaning unless filter through a child class such as student or teacher.
in the database this is hard to maintain as you can't have a person table that doesn't exist
This is where the idea of MVC and MVVM comes in as this encourages you to create a layered system so you have your bottom layer that manages the database object relationship and your top layer that handles your User object interaction
Related
I am new to programming and I have been into normalizing data and making a class diagram based on this normalized data. I seem to have trouble understanding how I would be working with this as I am trying to create an ASP.NET MVC application to work with this data.
This would be my class diagram:
Would this class diagram appear correct in the first place? Or should I make a relationship between Order and Stock? Or can there be multiple relationships (one going from stock class to order class and one going from stock class to products class)? Would I have to add StockId to the Order class (so that I can check if there is enough available of the product in the stock)?
How could my StockController class and a related Create view look like to assign a location to a product when adding new products to the Stock (so that the stock view would be updated)? I thought of adding new products in such StockController class aswell since I do not wish to add another view to display all products, as I want the Create view of the Stock class (thus using the Create method in the StockController) to do this job.
I would be making a model class specifically for Location and a controller with Enity Framework automatically generated views and CRUD operations to create a set of Locations and display an overview of this (how to generate this is not part of my question, but it's just to make the idea of my question a bit more clear).
I tried to let Entity Framework generate CRUD operations for the Stock class but this obviously would not work by default as I will not be inserting a new location, but actually assigning it to a (new) product. I wish to know how I can make assigning an existing location to a product, whilst creating a new product, possible in a Create method of a StockController class. I would also like to know how to make it possible to assign one or multiple locations in the Edit method. Could anyone give me an example of how I could achieve such? Am I correct to say that my model Stock class should contain a property which should contain a List<Location> Locations?
Edit: Please do not mind my typo's in the diagram.
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.
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.
I am making an library which will be used to talk with database using Entity framework. For different workflows I need different tables from database. So I decided to have separate models for separate workflows. But for some workflows one entity is used in multiple models. Now for one model I have modified my entity class (changed some getters/setters and added custom functions). But when I create new model for different workflow then model will generate entity with default names. I have to edit it again and code will be duplicated. Both are in different namespaces (one is Model1Namespace, second is Model2Namespace).
So what I exactly need is that if entity is used in different classes a single code is used (no duplicate code). What are the best practices? Do EF provide us something or we need to implement it ourself?
Example:
Database tables: TableA, TableB, TableC, TableD
Models: Model1 -> TableA, TableB
Model2 -> TableA, TableC,
Model3 -> TableC, TableD
Edit:
I have a database containing 4 tables (TableA, TableB, TableC, TableD). I create a Entity data model of the database which contains TableA and TableB. In entity designer view I modified names of properties of TableA Entity so that they are readable. Now I create another model which contains TableA and TableC. Now here I have to rename all properties of TableA again. Now this is repeat work. Now if I add some custom action to my Entity for Model1 then I have to write (copy) them to new Model2 Entity as well. I need to avoid this. As I really don't know how many models I will create. And if I have to do this stuff again and again then it will take lot of time.
Just curious.
Say I have a Base entity and I'm deriving about 10 different child entities from it using the Table Per Type method. I also have a generic repository which can fetch me data from each of these child entities. I eventually want to map each of the child entities to a separate view model and link each of the view models to its own grid (JqGrid) on my website, with each grid having its own Create, Read, Update, Delete methods. I can do all of that, but I'm not sure what's the proper way to go about it while keeping code to a minimum.
Right now, I have every field defined (from both the parent and child entity) in each of my view models. Is it better to have a "parent" view model and then deriving the child view models from it in order to mimic the inheritance structure of the entities? I wouldn't think so....having inheritance in view models doesn't make much sense to me.
Also, I really don't want to duplicate CRUD operations for each grid. Is that considered good practice? Should each view model have its own set of CRUD operations in this case?
Take 'Read' for instance. I'm basically returning JSON data based on the ID (key) field of the view model for each grid. And since all grids will have this ID column (part of the parent entity), should I only have one function that takes care of this for all grids? Should I be using reflections? Should I be making use of polymorphic properties of the parent/child entities?
Or is it better to keep these operations separate for each grid?
Hmmm..
It depends.
On top of all rules I would say: Keep it simple and don't repeat yourself.
Some comments:
Say I have a Base entity and I'm deriving about 10 different child
entities from it using the Table Per Type method.
Only as a side note: You are aware of the poor performance (at least for EF < 5) of TPT, right? It is something to keep in mind especially if the tables can be large or you have a deep inheritance hierarchy (entities derived from derived entities..., etc.)
I eventually want to map each of the child entities to a separate view
model
Which is in my opinion a good idea, alone for possible different validation rules you might apply to the ViewModels for each derived entity.
Is it better to have a "parent" view model and then deriving the child
view models from it in order to mimic the inheritance structure of the
entities?
To mimic the inheritance of entities is not a reason in my opinion. But if you have for example view validation rules on base model properties and they apply to all derived entities why not keeping those rules in one place - like a base ViewModel. Otherwise you had to repeat them in every derived ViewModel.
Should each view model have its own set of CRUD operations in this
case?
If the derived entities are "flat" (have only scalar properties and no navigation properties) you only would need something like:
Read: context.BaseEntities.OfType<T>().Where(...)...
Add: context.BaseEntities.Add(T entity);
Delete: context.BaseEntities.Remove(T entity);
Update: context.Entry(object o).State = EntityState.Modified;
All these methods work for base and derived entities. Why would you want to create such methods for each entity separately? You might need separate methods though in more complex situations, for example if derived entity number 7 has a navigation property to another entity and your view for that entity does allow to change relationships to the other entity. So, it depends. I would not start with duplicating methods that all do the same, rather refactor later when I see that I need special handling (unless maybe when you can foresee from the beginning that special handling is expected at some point during the project evolvement).
I'm basically returning JSON data based on the ID (key) field of the
view model for each grid. And since all grids will have this ID column
(part of the parent entity), should I only have one function that
takes care of this for all grids?
On repository/service side, yes, if only scalar properties are loaded for each derived entity. If you need navigation properties for derived entity 7 you may need something special (maybe an Include). Projecting the data into the ViewModels might be specific for every entity because you have separate ViewModels per entity.
Should I be using reflections?
WTF? Why that? Better not.
Should I be making use of polymorphic properties of the parent/child
entities?
??? (<- this is supposed to be a "Confused"-Emoticon)