Models Pattern in MVC - entity-framework

Is it a good practise to storage Models in this schema in solution?
Models folder, where I have POCO classes (or objects with EF Data Annotations) and main file MyDbContext.cs
ViewModels folder, where I storage all of ViewModels.
In ViewModels folder I have every single viewmodel class in separate XXX.cs file.
Should I do the same thing with Models folder and objects in this model? I mean, no one big file AccountModel.cs, but separate User.cs, ExternalUserProfiles.cs etc.
And at least question - when I have to use EF Fluent API with POCO pattern instead of Data Annotations EF?
Regards.

Is it a good practise to storage Models in this schema in solution?
Yes it is, when the project grows large you can go further and replace each folder with a separate assembly.
Should I do the same thing with Models folder and objects in this model?
I recommend this too, this way you will have a parallel hierarchy and a better organization. As for MyDBContext I usually move that to the data access assembly but you can keep it with the domain model if you want and move it only when the data access layer get huge.
when I have to use EF Fluent API with POCO pattern instead of Data Annotations EF?
You can use whatever you feel comfortable with. The only downside of using Data Annotations is that it is tightly coupled to the actual domain objects. Another things is that Fluent API is capable of doing things not achievable with Data Annotations and allows better separation of concerns.
You can even use both of them at the same time, just use the best tool for job.

Related

Exposed domain model in Java microservice architecture

I'm aware that copying entity classes and properties into DTOs is considered anti-pattern, so by Exposed domain model pattern the same #Entity can be used as both database entity class, and DTO for service and MVC layer. (see here https://codereview.stackexchange.com/questions/93511/data-transfer-objects-vs-entities-in-java-rest-server-application)
But suppose we have microservice architecture where the same set of properties is used as entity in one project with persistence, and as DTO in another project which uses the first one as a service. What's the proposed pattern in such a situation?
Because the second project doesn't need #Entity related functionality, and if we put that class in shared library, it will be tied unnecessary to JPA specific APIs and libraries. And the alternative is to again use separate DTO classes anti-pattern.
When your requirements for a DTO model exactly match your entity model you are either in a very early stage of the project or very lucky that you just have a simple model. If your model is very simple, then DTOs won't give you many immediate benefits.
At some point, the requirements for the DTO model and the entity model will diverge though. Imagine you add some audit aspects, statistics or denormalization to your entity/persistence model. That kind of data is usually never exposed via DTOs directly, so you will need to split the models. It is also often the case that the main driver for DTOs is the fact that you don't need all the data all the time. If you display objects in e.g. a dropdown you only need a label and the object id, so why would you load the whole entity state for such a use case?
The fact that you have annotations on your DTO models shouldn't bother you that much, what is the alternative? An XML-like mapping? Manual object wiring?
If your model is used by third parties directly, you could use a subclassing i.e. keep the main model free of annotations and have annotated subclasses in your project that extend the main model.
Since implementing a DTO approach correctly, I created Blaze-Persistence Entity Views which will not only simplify the way you define DTOs, but it will also improve the performance of your queries.
If you are interested, I even have an example for an external model that uses entity view subclasses to keep the main model clean.
Thank you for the answers, but emphasize in the question is on microservice (MS) architecture and reusing defined entity POJOs from one MS in another as POJOs. From what I've read on microservices it's closely related to another question - should MSs share any common functionality and classes at all, or be completely independent? It seems there is no definite agreement on it, and also no definite answer, or widely accepted pattern, to this.
From my recent experience here is what I adopted, and it works well so far.
Have common functionality across MSs - yes, in form of a commons project added as dependency to all MSs, with its dependencies set as optional. Share entity classes (expose them in commons) - no.
The main reason is that entity classes are closely related to data store for particular MS. And as the established rule is that MSs shouldn't share data stores, then it makes sense not to share entity classes for those data stores. It helps MSs to be more independent, and freedom to manage their data store in their own way. It means some more typing to add additional DTO classes and conversion between them, but it's a trade-off worth taking to retain MS independence. Reasons Christian Beikov and Maksim Gumerov mentioned apply as well.
What we do share (put in commons) are some common functionality and helper classes (for cloud, discovery, error handling, rest and json configuration...), and pure DTOs, where T is transfer between MSs (rest entities or message payloads).

I have three projects that share the same DB, whats the best way to use EF across all?

I have three projects (WCF projects, not clients), I have one database for all, now how will I use EF with this? should I make a fourth project which will have the db context and the entities and then add a reference to it in all three projects? or should I just have a separate context for each project and just add the tables i need for each project? some of the table are really used everywhere. so what's the best solution for this?
Another question: should I expose the EF db context in the separate project so other projects can access it? something like:
MySeparateProject myPr = new MySeparateProject();
using (var db = new myPr.DBContext())
{
// do stuff with entities
db.SaveChanges();
}
I think the cleanest thing to do is create a data access project (class library) that contains just your models and db context, and reference that from all of your other projects.
Some people will say that you should make one class library with just the models, and then have yet another that has the DbContext, and the have repository classes, and then.... I feel this is overkill for the majority of projects. Having the models and context in one place just makes it really easy to keep all the dependent projects consistently in sync when it comes to data access.
Here's a typical project structure for me:
Here, Squelch.Data contains all of my models and db contexts, Squelch.Core contains core business logic, and my two "applications" (Squelch.Portal ad CdrImport), and the various test cases, all reference these base class libraries.
I would create a separate data access project. It is good practice to separate your data layer out anyhow. Depending on the nature of the project and how you want to test it, you may want to take a look at something like the repository pattern (though there is debate about its value with EF).
http://msdn.microsoft.com/en-us/library/ff649690.aspx

Repository pattern with Entity Framework Entities vs Business Objects

In a code-first implementation of EF, used along with a Repository pattern, should the repository return business objects from the domain model, or simple entities from the data model?
From what I can tell, the point of Repository is to return business objects, not entities, so that you can do work with them. But most of the code examples I find are returning data models instead, which seems like a bad idea to me because what if the data source changes?
If you are using CodeFirst development you can easily use your business object as the data model as well. You can write Ef mappings in a separate DLL to remove the dependency of EF to business model. If you want to change the data source to another one instead of EF you can keep the same Business(domain) classes for that as well.

Entity Framework & Class Models in MVC

I'm new to the MVC way of developing applications and for the most part am enjoying. One thing I'm a bit confused about is the use of the Entity Framework. The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table. A couple of questions:
Why would I define a separate class file for a specific table if EF is building all of the classes that I need in the background?
From some of the validation approaches that I've seen, they want to define validation logic in the class related to a model for a table. If I'm using EF, will I have a .cs file describing the model and a .edmx describing that same table (in addition to its associated tables)?
If yes, how do you connect the .cs file to the .edmx definition so that CRUD flows easily from the EF?
Sorry if these seem like easy questions but I'm just trying to get my head wrapped around these fundamental concepts. Too many examples out there use only a single table where in my business, I NEVER write an application that uses a single table. There are always multiple tables in relation to each other with foreign keys. Thanks for your prompt responses.
For a tutorial that shows the use of partial classes -- in a Web Forms application but for MVC the same technique would be used -- see Adding Metadata to the Data Model in this tutorial:
http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-8
From your comment "The EF usually (at least in my experience) defines multiple tables and relationships through the .edmx table." it sounds like you are familiar only with Database First and Model First -- for an introduction to Code First and an explanation of the differences, followed by a series of tutorials with an MVC example using Code First, see this tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Good questions, Darryl. Here are my responses to your bullet points:
Defining separate model classes that match the data models that EF creates is generally a good idea for the simple sake of separating your data access "stuff" from your business model objects that will get used throughout your app. Some people don't like this approach because it creates some amount of overhead when it comes to mapping your entities to POCOs but, if you use a tool such as AutoMapper, the overhead is minimal. The benefit lies in you creating a layer of separation between you and your (likely) evolving data model.
You could define validation logic in a buddy class (just a partial class that sits along-side your entity) but that would mean that you would be using that entity across your app and some would debate that that isn't the best idea. The alternative method, as mentioned above, is to create your own POCOs to mirror the entities that EF creates and place your validation attributes on the POCOs.
I mentioned this in the previous item but the way to do this would be to define buddy classes. Give EF buddy classes a Google and you should find plenty of examples on how to do that.
Just to add to all of this, if you choose to create POCO classes that mirror your EF entities, tools like AutoMapper can handle fairly complex relationships when it comes to mapping classes. So, if you have foreign key relationships in your data model, AutoMapper can understand that and map your POCO classes accordingly (i.e.: You have an entity that has a 1-to-many relationship and a POCO with a list of objects to mirror that relationship.)
I hope some of that helps...

zend models architecture

Let's say I have two tables in a database: projects and users. I create two models, that extend Zend_Db_Table_Abstract: Model_DbTable_Users and Model_DbTable_Projects.
Now, is it a good pattern to create an instance of Model_DbTable_Projects inside the Model_DbTable_Users class ? In other words: is it OK to put any logic in this model, or should I create another class, that uses Model_DbTable_Users and Model_DbTable_Projects?
I use to put all the logic in models, that extend Zend_Db_Table_Abstract, but in large projects it can make code very unclean. So, can you give me any advice on models architecture(links on articles would be great!).
I was the project lead for the Zend Framework project through version 1.0. My contributions were mainly in the Zend_Db component.
I frequently advise that people should use the Domain Model pattern and avoid the Anemic Domain Model antipattern. Remember that a Table is not a Model.
Your Model is a class (extending no base class) for code that encapsulates your business logic. The relationship between a Model and a Table isn't IS-A, it's HAS-A (or HAS-MANY). The Model treats database persistence as an implementation detail. The consumer of a Model should have no clue about your database structure (this allows you to change database structure without changing the Model's interface).
I'm basically repeating the answer I gave to Models in the Zend Framework.
Here is some more reading:
http://weierophinney.net/matthew/archives/202-Model-Infrastructure.html
http://blog.astrumfutura.com/archives/373-The-M-in-MVC-Why-Models-are-Misunderstood-and-Unappreciated.html
http://n4.nabble.com/Another-Model-Design-Thread-td670076.html