Data Access Pattern Like Repository but Not Completely - c#

I'm working on a project with a system that holds data and I'm thinking about using a data access approach to get data to hand it off to my components on the presentation side of things. I'm thinking of this as an N-tier architecture. Here's my thought:
Presentation layer (WebForms and User Controls)
\/
Data access layer (this is where my question is)
\/
Business objects (a C# class for each entity in the system)
\/
Existing APIs to get data from database (MS SQL-driven)
In my DAL, I want to use a particular API mechanism from the system to get the business objects so I can pass them to my presentation components. I am aware of the repository pattern where I create various utility repository classes to "get a bunch of the X business objects". E.g. say I have a business object called Article, I could have an ArticleRepository and my "Article listing page" would call that repository and get me a collection of Article. This is nice, but might be overkill at the DAL for me. Is there a name of doing something else like just having a static GetAll() method on my business object? So isntead of:
var repo = new ArticleRepository();
IEnumerable<Article> articles = repo.GetAll();
I'm thinking something simple like this:
IEnumerable<Article> articles = Article.GetAll();
Where the Article class is both my business object with relevant properties and even helper methods, but also has a static GetAll() method. Is there a name for this approach? Is it a bad idea to create this slimmed down pseudo-repository?
I ask all this because simply put, I will have LOTS of repository classes to do this because I have lots of business objects, all with unique queries to get them from the system.

Don't know about the name of your architecture, but IMHO DAL should take care of persistence thus dealing directly with DB API.
From my experience, there's no excuse for thinking that some good practice is overkill :)
Generic repository with EF is pretty simple to implement and will make you smile in the future.

Related

What is the standard I should use in MVC coding

Based on the answers mentioned here, I understood that I should put the business logic inside the model itself, while in my program I am using EF directly inside the actions of the controller for example to get the list of cars from the database directly I am doing the following:
public ActionResult CarList()
{
using(var _db = new CarRentEntities())
{
var result = _db.Cars.Where(m=>m.Active);
return View(result);
}
}
what is the impact on my website performance if I will use the mentioned above code inside controller or inside Model?
which method I should use? for example if I want to work with a team, is there a standard I should follow to separate the code, kindly advise
for using the repository pattern: I read that we should not use if as mentioned for example here , i will copy some of what mentioned:
The single best reason to not use the repository pattern with Entity
Framework? Entity Framework already implements a repository pattern.
DbContext is your UoW (Unit of Work) and each DbSet is the repository.
Implementing another layer on top of this is not only redundant, but
makes maintenance harder.
if my database contains the following tables: Manufacturers , Cars , Rent , Clients , rent class is the a table with 2 foreign keys between Clients and Cars and contains other detailed fields.
how to deal with Rent Object which need to get data from 2 different repositories Cars and Clients in order to display the renting grid based on search criteria entered by the user, if I will use the repositories Cars and Clients , they have their own dbContext, BOOM my head cannot understand this technique, kindly advise
The answer to your question is, it does not really affect performance but it will definitely become an issue in terms of maintainability as the application grows bigger. You can adopt the SOLID architecture principles: SOLID architecture principles using simple C# examples. This enables you to develop high quality software.
You can create a multi-layered application:
Interface Layer - MVC application
Business Layer - Class Library with classes with logic
Data Access Layer - Database Contexts and Repositories, unit of work with CRUD operations
Shared layer - Logging, AppSettings, validations, utilities, extensions, constants, enums
Having your application in this structure would require you to consider things like inversion of control, dependency injection and many more to ensure loosely coupled classes, easy unit testing and most of all a solid application.
You can also read this: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
Generally the Model is a "unit" - i.e. it is a model of the data you want to display. The Controller is an "integrator" - i.e. it pulls together the various resources required to render your web page. You may wish to create a database fascade class which does something like this;
public ActionResult CarList()
{
using(var carStore = new Factory.CreateCarStore())
{
var result = carStore.GetActiveCars();
return View(result);
}
}
To separate your database access from your web controller (this would make it more test-able as well because you can substitute a different CarStore implementation (i.e. a Test XML data set) for testing purposes.

S#arp Architecture: Where to put this domain logic

re: S#arp Architecture
A bit of a noob question about where to put certain sorts of domain logic with S#arp. OK, so imagine this domain rule:
When asking for a specific chat room by name, return the room if it already exists, or else create a new one with that name and return it.
Is this Domain Logic? In which case, how do I implement it in my Entity object (as I seem to need access to the Repository to do it)
Is this Controller Logic? In which case I guess I stick it in the MVC controller, easy enough.
Is this Data Access Logic? In which case I build it into the Repository object and the Contoller calls it. Again, easy enough.
I reckon this is Domain Logic, but then I'm not sure how to built it into my Entity. As Entities dont seem to access to Repositories (or am I missing something?).
From the way you've described it, I'd say this would best go in the Application Services layer. (the Tasks layer in the WhoCanHelpMe? example project). For me this is application logic rather than domain logic.
For the other options:
Sharp is designed intentionally so that Entities don't access the Repositories. (You'll find quite a lot of articles around on why Entities should be persistence-ignorant.)
In general the controllers aren't really meant to contain any business logic directly - for readability, testability, etc. (Personally I'm comfortable putting logic in there initially and then refactoring it out.)
One reason I'd be uncomfortable putting the logic directly in a repository is clarity. If you have methods on IChatRoomRepository:
ChatRoom GetRoomByName (string name);
ChatRoom GetRoomById (int id);
typically GetRoomById would return null if there is no room for the given id, so it's not too obvious that the first method will silently create (and presumably persist?) a room if you don't already have one.
More conceptually, from DDD Quickly (p56):
We should not mix a Repository with a Factory. The Factory should create new
objects, while the Repository should find already created objects. When a
new object is to be added to the Repository, it should be created first
using the Factory, and then it should be given to the Repository
which would suggest that if you're trying to implement the repository pattern, the creation of a new chat room should happen outside the repository.

Services and Repositories in DDD (C#)

How do Services and Repositories relate to each other in DDD? I mean, I've been reading up on DDD for the past 2 days and everywhere I go, there's always a Service layer and there's always a Repository layer. How do these differentiate or compliment each other?
From what I've read, isn't the Repository the layer responsible for delegating interactions between the application and the data?
So, what's the need for the Service layer if it has to implement the Repository to interact with the data anyway even though the Repository probably already implements the methods needed to do so?
I'd appreciate some enlightenment on the subject.
P.S. Don't know if this will help any, but I'm working with an ASP.NET MVC 2 application in which I'm trying to implement the Repository pattern. I just finished implementing the Dependency Injection pattern (for the first time ever)...
UPDATE
Okay, with so many answers, I think I understand what the difference is. So, to review (correct me if I'm wrong):
A Repository layer interacts only with a single object out of the database or the ORM, IEmployeeRepository -> Employee.
A Service layer encapsulates more complex functionality on objects returned from Repositories, either one or multiple.
So, then I have a sub question. Is it considered bad practice to create abstract objects to be sent to my views? For example an AEmployee (A for abstract because to me I means interface) which contains properties from Employee and X or X?
Actually, one more subquestion. If a Service layer can be considered "tuned" for an application does it need to be implemented with an interface?
The Service will use a Repository to retrieve an Entity and then call methods on it (the Entity) to perform the Command/task.
True, a repository works with data (ie. SQL, Webservice etc.) but that's the only job. CRUD operations, nothing more. There is no place for stored procedure based busines logic.
The service (or business logic layer) provides the functionality. How to fullfill a business request (ie. calculate salary), what you have to do.
Oh, and this is a really nice DDD book:
http://www.infoq.com/minibooks/domain-driven-design-quickly
As a concrete example a Shopping Cart application might have the following services:
ShoppingCartService - manages a cart of items with add/remove/update support etc.
OrderService - take a cart, converts it to an order and handles the payment process etc.
each of these services needs to talk a "data source" for CRUD operations. This is where the Repository pattern comes in handy as it abstracts the loading and saving of data to and from the data source be it a database, web service or even in-memory cache.
When you want to create a quick prototype of your application without having to deal with database setup, schema, stored procedures, permissions, etc. you can create a cache or fake repository in a matter of minutes.
For the example above your prototype might start off with the following:
FakeCustomerRepository
FakeAddressRepository
FakeCartRepository
FakeCartLineItemRepository
FakeOrderRepository
FakeOrderLineItemRepository
once your prototype is ready to evolve to the next level you can implement these against a real database:
SQLCustomerRepository
SQLAddressRepository
SQLCartRepository
SQLCartLineItemRepository
SQLOrderRepository
SQLOrderLineItemRepository
From what I can remember, the repository is the final class before the data. The service class can act on data retrieved from the repository. The repository is really just meant to get data to somebody else to do the work. The service layer can provide things such as business logic that all data must pass through. It could also provide for a translation between the application logic and the data layer. But again, this is just what I can remember.
There's no golden standard that defines a service or a repository. In my applications a repository is (as you say) an interface into a database. A service has full access to a repository - but the service exposes a subset of functionality to its consumers.
Think of the repository as more low level. The repository has to expose many ways of accessing the underlying database. A service might combine calls to a repository with other code that only makes sense at a code level (i.e. not in the database), such as access to other state in the application, or validation/business logic that can't easily be applied in a database.

.net, C# Interface between Business Logic and DAL

I'm working on a small application from scratch and using it to try to teach myself architecture and design concepts. It's a .NET 3.5, WPF application, and I'm using Sql Compact Edition as my data store.
I'm working on the business logic layer, and have just now begun to write the DAL. I'm just using SqlCeComamnds to send over simple queries and SqlCeResultSet to get at the results. I'm starting to design my Insert and Update methods, and here's the issue - I don't know the best way to get the necessary data from the BLL into the DAL. Do I pass in a generic collection? Do I have a massive parameter list with all the data for the database? Do I simply pass in the actual business object (thus tying my DAL to the conrete stuff in the BLL?).
I thought about using interfaces - simply passing IBusinessObjectA into the DAL, which provides the simplicity I'm looking for without tying me TOO tightly to current implementations. What do you guys think?
I don't think there is a simple answer to your questions because there are many options depending on the circumstances. I have found it helpful to read the two books below to help me understand the problems you describe better.
MS .NET: Architecting Applications for the Enterprise (Esposito, Saltarello)
MS Application Architecture Guide, 2nd edition.
The second book is available online. Look here.
I think it is OK to pass the Business object to the Data Access Layer. I think the BLL's job is just to work with its objects, to check if all rules are being followed, about what can be saved, by whom, on what fields, time, etc.
Once it has done that it should pass it to the DAL, and I think it is IT'S job to figure out how to convert what it got into something that can be persisted, but it wont check what is being persisted or read or by whom, it will just do it. This could be straight foward, a la linq, but if your logic mdoels do not match your data model 1:1, then the DAL should do all the conversion.
About tying your DAL to the stuff in the BLL, I think you should worry about the other way around, tying your BLL to your DAL. I would use an interface to represent your DAL (as in IRepository) that way you can make your BLL call any kind of persistance mechanism just by changing the type of IRepository it is using (extra points if you use IoC :P). The concrete classes that implement the IRepository would be tied to the business objects, but they have to know what is it that they are saving don't they? while the BLL does NOT have to know what is doing the saving.
To pass business object in the DAL is the simpler and fastest method. It works in small projects, but have same disadvantages:
1) Business Objects are part of BLL layer, and if you pass objects in BLL then DAL becomes dependent of BLL. low layer knows about upper one - this contradicts the idea of layers at all.
2) Business Object are usially very complex to save it directly in BD. In this case it is better to introduce new "Mappers" intermediate layer.
To overcome all these issues I usially make interface to DAL independent of Business Objects. I use "Row" classes instead - representation of one record in the database or XML. In .NET 3.5 linqtosql autogenerated classes can be used for this purpose.
If I was in your position, I'd probably use LINQ to SQL to define my data access layer - it'll save you lots of work maintaining all that SqlCeFooBar stuff and give you a designer (of sorts) for maintaining your database that you would otherwise lack, using SQL CE.
So in that case, I'd probably couple the business logic layer pretty tightly to the entities exposed by the L2S layer. The justification being that the entities are the business objects, albeit devoid of any services.
I probably wouldn't let the entities get as far up the hierarchy as the UI though. At that level, it makes much more sense to use a model specifically for the view - especially given that you're using WPF.
Of course, all of this depends upon the size and complexity of your application. I'm assuming it's a fairly small scale application (single user?) given that you're using SQL CE.

Design of Business Layer

We are currently revamping our architecture and design of application. We have just completed design of Data Access Layer which is generic in the sense that it works using XML and reflection to persist data.
Any ways now we are in the phase of designing business layer. We have read some books related to Enterprise Architecture and Design so we have found that there are few patterns that can be applied on business layer. Table Pattern and Domain Model are example of such patterns. Also we have found Domain Driven Design as well.
Earlier we decided to build Entities against table objects. But we found that there is difference in Entities and Value Objects when it comes to DDD. For those of you who have gone through such design. Please guide me related to pattern, practice and sample.
Thank you in advance! Also please feel free to discuss if you didn't get any point of mine.
#Adil, this is not an answer to your original question, but I would advise you to revise your decision to roll your own data access layer. You note that you'd like to go to NHibernate: just do it now.
IMO, writing an ORM is a waste of time unless you have some very specific restrictions. There are a wealth of options out there, with hundreds of hours of effort poured into them already. Leverage it! LINQ2SQL, Entity framework, NHibernate, Subsonic, LLBLGen are all good, and there are more out there.
Note too that if you roll your own you won't get to use the goodness that is LINQ without a lot of effort.
As far as layering goes, try not to go nuts: keep the number of layers in check and concentrate instead on building a worthwhile interface between them to guard against your abstractions leaking.
I've seen a number of very "patterned", beautifully layered projects that in use end up with logic everywhere and persistence abstractions leaked all over the place. Keep it simple!
CSLA.NET works pretty well as a base for the business layer.
#Adil,
I'm not very experient user, anyway, this is the kind of model I'm using (also with NHibernate).
GUI - with all the web forms and so on
BLL - The catalogs that are responsible for creating instances of new objects
DAL - The place where classes responsible for interaction with NHibernate are implemented. The NHibernate mapping files are here.
Model - Class Library that is used by the BLL and DAL for data transfer object between.
Different patterns are used. For example, the BLL and DAL have a Factory class that allow access to an interface. The catalogs are Singleton classes. All of the catalogs are accessible using a master Singleton class representing my business logic top object (for example "Enterprise" => "Enterprise.PeopleCatalog".
Anyway, hope it helped...
#AngryHacker, thanks for the tip, could you give an example of CSLA.NET?

Categories

Resources