In MS MVC, are Poco classes to be defined in the Models namespace but outside of a repository class? - asp.net-mvc

I think I am very close to assembling an MVC repository correctly but just falling apart at the fringe. I created an MVC project with a repository and am returning data successfully, but not accurately as it pertains to DDD. Please tell me where I am incorrect in terms of strict DDD assembly. I guess if the topics are too wide, a book suggestion would be fine. I hope that I am specific enough in my question.
This was one question but I separated them for clarity: Do you create a single namespace for all repository classes called MyStore.Models? Create a repository class for each entity like Product within the Models namespace? Do you put the Pocos in their own classes in the Models namespace but not part of the Repository class itself?
I am currently using Pocos to cut out entities from Linq statements, returning groups of them within IQueryable wrappers like so. I guess here you would somehow remove the IQueryable and replace it with some type of Lazy load? How do you lazy load without being dependent on the original Linq to Sql?
public IQueryable<Product> GetProducts(...) {
return (from p in db.Products
where ...
select new myProductPoco { // Cut out a Poco from Linq
ID = p.ID,
Name = p.Name,
...
});
}
Then reference these in MVC views within the inherit page directive:
System.Web.Mvc.ViewPage<IQueryable<MyStore.Models.Product>>
However, the nested generics looks wrong. I assume this requires a re-factor. Where do you define View Model classes that contain references to Entities? Within the controller class (nested class)?

As book suggestions, try Eric Evan's Domain-Driven Design, and maybe Martin Fowler's Refactoring.

Also try Domain Driven Design Quickly produced by InfoQ. It's free to download or $30 in print.
"Domain-Driven Design Quickly was
produced by InfoQ.com, summarized
primarily by Abel Avram and with Floyd
Marinescu as managing editor. Special
thanks to Eric Evans for his support
and Vladimir Gitlevich and Dan Bergh
Johnsson for their detailed reviews.
The intention of this book is to get
an introduction to Domain-Driven
Design into as many hands as possible,
to help it become mainstream." --
InfoQ

Related

Which layer should i place .edmx and generated POCO classes?

This is regarding a layered design with EF DB First model.
So far i have not used Entity Framework before, used only Entities and placed on a different project with Domain/ DTO sub folders. Also referred the same in DataAccessLayer, Business Layer and MVC application and written a code with usual ADO.Net queries and prepared POCOs of my entities. No issues.
Now we are developing an application using Entity Framework DB First model. We choosen this DB First model, as the DB Design is not in our control. It is done by DBA.
I thought of reusing the old simple design here. But not sure where/which layer I should exactly fit the edmx file and the generated POCO classes. I didn't find any samples with layered architecture style uses DBFirst approach.
I referred this. http://aspnetdesignpatterns.codeplex.com But they use NHybernate
Here is the highlevel overview of old design.
Any suggestions on design/samples, please you are welcome.
Edit:
From the below answer, I think the entity framework produces the POCOs we could rename existing Entities/Domain layer to Domain Layer and putting the generated POCO classes there. Also we can simply keep .edmx in DataAccessLayer with the list of IRepository classes that wraps EF for TDD. Does this makes sence? or any valuable points?
Update:
Currently i removed DataAccessLayer and keep only Entities layer which
has a model.edmx file and classes generated by EF and also all
Repository classes implementing IRepository. I refer this into
Business Layer, MVC as well. Am i doing right? I feel like i am doing
a bad design :( Please suggest/help
Because you're unfortunately severely handicapped by the decision to create the database first, you will need to use an Anti-Corruption layer per Eric Evans' Domain-Driven Design.
This is a good solution for what to do when you're given a shitty interface that you absolutely must code against - make an interface wrapped around the DB that behaves the way you want it to. Do not expose any EF classes directly to anything except the anti-corruption layer itself.
Here's a reading example:
public class SomeReadService : ISomeReadService {
public SomeViewModel Load(Guid id) {
using (var dbContext = new DbContext()) {
// Query the DB model, then *map* the EF classes to SomeVieWModel.
// This way you are not exposing the shitty DB model to the outside world.
}
}
}
Here's a writing example:
public class SomeRepository : ISomeRepository {
public SomeDomainObject Load(Guid id) {
using (var dbContext = new DbContext()) {
// Map the EF classes to your domain object. Same idea as before.
}
}
}
I would still try to demonstrate to the client that having a separate team design the DB will be a disaster (and my experience strongly indicates that it will). See if there is some way you can provide the feedback that will demonstrate to the client that it would be better if you designed the DB.
Please see the SO link for similar kind of question below:
With a database-first approach, how do I separate my Core and Infrastructure layers?
Hope this helps !!
In my opinion, Entity Framework used correctly negates the need for a seperate DAL. I think of EF as my DAL. It allows you to concentrate on the business part more. EF does all the data access code for you. You can simply use your EF context in your business layer. To me, this is one of the best benefits of EF; that it is your DAL.
Depending on how you separate your layers (different assemblies or different folders within an assembly) depends where you put your POCO classes. If different assemblies (which is overkill for most projects) then a 'Common' assembly referenced by all others is the place to put POCO classes. If different folders, then a folder named 'Models' or 'DomainModels' is the place.
Specifically for an MVC application, I would put my POCO classes in the 'Models' folder (I also have a 'ViewModels' folder), and my .Edmx in a BLL folder which I sometimes call 'Logic'.
If you need a loosely coupled architecture for testing, then a folder named Repositories with the EF context wrapped in your own repository pattern is the way to go.
Edit:
The Short Answer is Data Access Layer (DAL)
You need to Enterprise architecture and it changes according your needs, but in your case Model Driving Design Pattern is the solid solution.
You can use MVC and you can drive your model from Poco or other entities like NHibernet etc.
No any importance about code-first or db-first, it is interesting just with the architecture creation phase.

MVC, Strongly Typed Views and Entity Framework dilemma

I've read quite a few Q & As relating to logic in views within an MVC architecture and in most cases I agree that business logic shouldn't live in a view. However having said this, I constantly question my approach when using Microsoft's MVC Framework in conjunction with the Entity Framework because of the ease of accessibility to foreign key relationships a single entity can give me which ultimately results in me performing Linq to Entities queries inline within a View.
For example:
If I have the following two entities:
Product ([PK]ProductId, Title, Amount)
Image ([PK]ImageId, [FK]ProductId, ImageTitle, DisplayOrder)
Assuming I have a strongly typed Product view and I want to display the primary image (lowest display order) then I could do something like this in the view:
#{
Image image = (from l in Model.Image
orderby l.DisplayOrder
select l).FirstOrDefault();
}
This is a simple example for demonstration purposes, but surely this begins to bend the rules in relation to MVC architecture, but on the other hand doing this in the Controller and then (heaven forbid) jamming it into the ViewBag or ViewData would surely be just as much of a crime and become painful to manage for more than a few different related classes.
I used to create custom classes for complex Models, but it's time-consuming and ugly and I no longer see the point as the Entity Framework makes it quick and easy to define the View to be the primary Model (in this case a Product) and then easily retrieve all the peripheral components of the product using Linq queries.
I'd be interested to know how other people handle this type of scenario.
EDIT:
I also quite often do things like:
#foreach(Image i in Model.Image.OrderBy(e => e.DisplayOrder).ToList())
{
<img ... />
}
I'm going the 'custom classes for Models' way, and I agree it's time consuming and mundane, hence tools like http://automapper.codeplex.com/ have been created, to accompany you with this task.
Overall, I'm having similar feelings to yours. Reading some stuff saying it's good to have your domain model unrelated to your storage, then different class for your view model than the domain model, and then seeing that libraries actually seem to 'promote' the easy way (data annotations over your domain classes seem to be simplier than EF fluent interface etc etc).
At least we've got the choice I guess!
Model binding There is also issue that when you want to POST back the model data and store it in the database, you need to be careful and make sure MVC model binders bind all fields correctly. Else you may loose some data. With custom models for views, it might be simplier.
Validation
MVC gives you a way to validate using attributes, when you use viewmodels, you can freely pollute it with such annotations, because it's view specific (and validation should be view/controller action specific as well). When you use EF classes, you would be polluting those classes with unrelated (and possibly conflicting) logic.

Some issues about Rob Conery's repository pattern

Please read my update at the end of question after reading the answers:
I'm trying to apply repository pattern
as Rob Conery's described on
his blog under "MVC Storefront".
But I want to ask about some issues
that I had before I apply this design
pattern.
Rob made his own "Model" and used some
ORM "LINQ to SQL or Entity Framework (EF)" to map his database to
Entities.
Then he used custom Repositories which
gives IQueryable<myModel> and in
these repositories he made sort of
Mapping or "Parsing" between ORM Entities and his Model classes.
What I'm asking here:
Is it possible to make custom mapping between ORM Entities and my
model "classes" and load just
properties that I want? I hope
the point is clear.
Update For POCO
**
This is what I decided after many of suggestions and many of tries:
**
After all and with respect to Mr. Rob Conery's opinion I've got better solution as:
I built my model as "POCOs" and put them in my "Models Layers" so they had nothing to do with the "edmx" file.
Built my repositories to deal with this "POCO" model dependent on "DbContext"
Then I created a "ViewModels" to get just the information that needed by view from those repositories.
So I do not need to add one more layer to be between "EF Models" and "My Model". I just twist my model a little and force EF to deal with it.
As I see this pattern is better than Rob Conery's one.
Yes, it's possible if you're using LINQ to SQL. All you need to do is use projection to pull out the data you want into an object of your choosing. You don't need all this decoration with interfaces and whatnot - if you use a model specific to a view (which it sounds like you need) - create a ViewModel class.
Let's call it ProductSummaryView:
public class ProductSummaryView{
public string Name {get;set;}
public decimal Price {get;set;}
}
Now load it from the repository:
var products= from p in _repository.GetAllProducts
where p.Price > 100
select new ProductSummaryView {
Name=p.ProductName,
Price=p.Price
}
This will pull all products where the price > 100 and return an IQueryable. In addition, since you're only asking for two columns, only two columns will be specified in the SQL call.
Not a dodge to your question, but it's ultimately up to you to decide how your repository would work.
The high-level premise is that your controller would point to some repository interface, say IRepository<T> where T : IProduct. The implementation of which could do any number of things---load up your whole database from disk and store in memory and then parse LINQ expressions to return stuff. Or it could just return a fixed set of dummy data for testing purposes. Because you're banging away on an repository interface, then you could have any number of concrete implementations.
Now, if you're looking for a critique of Rob's specific implementation, I'm not sure that's germane to Stack Overflow.
While it's possible to populate part of an object based on a query of a subset of the columns for that object using a query (which has nothing to do with the repository pattern), that's not how things are "normally" done.
If you want to return a subset of an object, you generally create a new class with just that subset of properties. This is often (in the MVC world view) referred to as a View Model class. Then, you use a projection query to fill that new class.
You can do all of that whether you are using the repository pattern or not. I would argue there is no conflicting overlap between the two concepts.
DeferringTheLoad
Remember that IQueryable defers all the loading up to the last responsible moment. You probably won't have to load all the data using the LINQ operators to get the data you want. ; )
Respecting the dependency in domain classes in views, I will say NO. Use a ViewModel pattern for this. It's more maintainable; you could use AutoMapper to avoid the mapping problems, and they are very flexible in composite views scenarios : )
According to the new question...The answer is yes, you can. Just as Rob Conery says, use projection ; ):
var query = from p in DataContext.Persons}
select new Persons
{
firstname = p.firstname,
lastname = p.lastname
});

Use of "stores" within a web application

I see heavy use of "store" objects in the web app I am working on. Is there a name for this pattern and would you say these types are in the BLL or DAL?
These stores contain fragments of what I would consider a classical DAL type, associated with a single type.
For example, we have a TabStore containing methods for the persistance and retrieval of Tabs. Within each method in the TabStore there is code to invoke the appropriate NHibernate query.
What are the pitfalls (if any) of working with this pattern? Is it really a simple attempt to separate what might once have been a monolithic Dal type into more manageable, smaller types?
Example method:
public IList<Tab> GetAllTabInstancesForUserId(Guid userId)
{
IList<Tab> tabInstances =
UoW.Session.CreateQuery("from Tab t where t.UserId=:userId order by t.TabOrder")
.SetGuid("userId", userId)
.SetCacheable(true)
.List<Tab>();
return tabInstances;
}
It may be what is more commonly known as a Repository.
The abstract Repository belongs in the Domain Model, but should be implemented by concrete classes in a separate Data Access Component.
If I understand the question correctly, "stores" are more related to DAL than to BLL, since there should be little logic in them - after all their role is just "storing".
Some more details would definitely be helpful, including code snippets where the 'store' is used...
But based on what you have in your question, it sounds like the developers used the term 'store' instead of 'Repository' which implies the Repository Pattern (which are related to your Data Acess Layer).
After your update...it definitely seems like what the developers originally called a 'store' is a 'repository'.

Is my ASP.NET MVC application structured properly?

I've been going through the tutorials (specifically ones using Linq-To-Entities) and I understand the basic concepts, however some things are giving me issues.
The tutorials usually involve only simple models and forms that only utilize basic create, update and delete statements. Mine are a little more complicated, and I'm not sure I'm going about this the right way because when it comes time to handle the relationships of a half dozen database objects, the tutorials stop helping.
For the post method, the usual way of performing CRUD operations
entities.AddToTableSet(myClass);
entities.SaveChanges();
Won't do what I want, because a fully implemented class isn't getting posted to the controller method. I may post individual fields, form collections, or multiple DTO objects and then call a method on a service or repository to take the information I receive from a form post, along with information that it needs to query for or create itself, and then from all of those things, create my database object that I can save.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id, [Bind(Exclude = "Id")] ClassA classA,
[Bind(Exclude = "Id")]ClassB classB)
{
// Validation occurs here
if(!ModelState.IsValid)
return View();
try
{
_someRepositoryOrService.Add(id, classA, classB);
return RedirectToAction("Index", new { id = id });
}
catch(Exception ex)
{
// Logging and exception handling occurs here
}
}
public void Add(int id, ClassA classA, ClassB classB)
{
EntityA eA = new EntityA
{
// Set a bunch of properties using the two classes and
// whatever queries are needed
};
EntityB eB = new EntityB
{
// Set a bunch of properties using the two classes and
// whatever queries are needed
};
_entity.AddToEntityASet(eA);
_entity.AddToEntityBSet(eB);
_entity.SaveChanges();
}
Am I handling this correctly or am I bastardizing the framework? I never actually use an entity object directly, whenever I query for one I put the information I need in a DTO and base my Views off of that. Same goes with the creation. Is this allowed, or is my avoidance of using entities directly going against the purpose of using the framework?
Edit: I'm also worried about this approach because it requires empty constructors to properly do the LINQ queries because of this error message:
Only parameterless constructors and
initializers are supported in LINQ to
Entities.
This isn't a big deal since I rarely need logic int the constructors, but is this an issue to have no constructors and only public properties?
_someRepositoryOrService.Add(id, classA, classB);
I would say you couple your repositories with presentation layer. This shouldn't be. Your repositories should only work with entities. Next, notice how your Add method
public void Add(int id, ClassA classA, ClassB classB)
breaks Separation of Concerns (SoC). It performs two tasks:
map view data into entities
save to repository
Obviously the first step should be done in presentation layer. Consider using model binders for this. It can also help you to solve the constructors problem, since your model binders can be made aware of the construction requirements.
Check also this excellent post by Jimmy Bogard (co-author of ASP.NET MVC In Action) about ViewModels. This might help you to automate mapping. It also suggest a reversed technique - make your controllers work with entities, not ViewModels! Custom action filters and model binders are really the key to eliminate routine that that don't really belong to controllers but rather an infrastructure detail between view and controller. For example, here's how I automate entities retrival. Here's how I see what controllers should do.
The goal here is to make controllers contentrate on managing business logic, putting aside all the technical details that do not belong to your business. It's techical constraints that you talk about in this question, and you let them leak into your code. But you can use MVC tools to move the to them infrastructure level.
UPDATE: No, repositories shouldn't handle form data, that's what I mean by "coupling with presentation". Yes, repositories are in the controller, but they don't work with form data. You can (not that you should) make form work with "repositories data" - i.e. entities - and that's what most examples do, e.g. NerdDinner - but not the other way. This is because of the general rule of thumb - higher layers can be coupled with lower ones (presentation coupled with repositories and entities), but never low level should be coupled to higher ones (entities depend on repositories, repositories depend on form model, etc).
The first step should be done in the repository, that's right - except that mapping from ClassX to EntityX does not belong to that step. It's mapping concern - an infrastructure. See for example this question about mapping, but generally if you have two layers (UI and repositories) they shouldn't care about mapping - a mapper service/helper should. Beside Jimmy's blog, you can also read ASP.NET MVC In Action or simply look at their CodeCampServer for how they do mapping with IEntityMapper interfaces passed to controller constructors (note that this is more manual and less-work approach that Jimmy Bogard's AutoMapper).
One more thing. Read about Domain Driven Design, look for articles, learn from them, but you don't have to follow everything. These are guidelines, not strict solutions. See if your project can handle that, see if you can handle that, and so on. Try to apply this techniques since they're generally the excellent and approved ways of doing development, but don't take them blindly - it's better to learn along the way than to apply something you don't understand.
I would say using DTOs and wrapping the Entity Framework with your own data access methods and business layer is a great way to go. You may end up writing a lot of code, but it's a better architecture than pretending the Entity Framework generated code is your business layer.
These issues aren't really necessarily tied to ASP.NET MVC in any way. ASP.NET MVC gives basically no guidance on how to do your model / data access and most of the samples and tutorials for ASP.NET MVC are not production worthy model implementations, but really just minimal samples.
It seems like you are on the right track, keep going.
In the end, you are using Entity Framework mostly as a code generator that isn't generating very useful code and so you may want to look into other code generators or tools or frameworks that more closely match your requirements.

Resources