I recently learned some knowledge about asp.net mvc, so I want to use a small project to train my hands and improve my code and thinking skills. before that, it was very easy to do east and west. We directly used the software to generate code and generate a simple three-tier architecture as the overall framework of the project. The database access layer uses ado.net. it is quite troublesome to do this. If you want to change the project database, you need to add a table to the database, add a field to the table, or use an orm framework instead of ado.net to access the database, in this way, the overall project should be dynamic, and we need to rethink how to build it to solve these problems.
About database access layer
Database Access driver layer-we all know that EF, NH, and Ado.net are implemented by yourself, and they all provide a bridge for us to access the database or perform database operations, of course, the database may also be different databases, which are determined based on the project requirements. The selection depends on the situation. here I used EF -- model-first. I designed the model directly in edmx and then generated the entity and database, as shown in the following figure. A simple permission management (not fully implemented yet) is implemented )..
Copy codeThe Code is as follows: public class BaseRepository <T>: IDAL. IBaseRepository <T> where T: class
{
Private DbContext container = EFContentFactory. GetCurrentContext ();
# Add region
Public T AddEntity (T entity)
{
Container. Set <T> (). Add (entity );
Return entity;
}
# Endregion
# Delete region
Public bool DeleteEntity (T entity)
{
Container. Set <T> (). Attach (entity );
Container. Entry (entity). State = EntityState. Deleted;
Return true;
}
# Endregion
# Modify region
Public bool UpdateEntity (T entity)
{
Container. Set <T> (). Attach (entity );
Container. Entry (entity). State = EntityState. Modified;
Return true;
}
# Endregion
# Region Query
Public IQueryable <T> GetEntities (Func <T, bool> lambdaWhere)
{
IQueryable <T> entities = container. Set <T> (). Where (lambdaWhere). AsQueryable ();
Return entities;
}
# Endregion
# Region Paging
Public IQueryable <T> GetEntitiesByPageIndex <TS> (int pageIndex, int pageSize, out int totalCount, Func <T, bool> lambdaWhere, Func <T, TS> orderByRole, bool descending)
{
Var temp = container. Set <T> (). Where (lambdaWhere). AsQueryable ();
TotalCount = temp. Count ();
If (descending)
{
Temp = temp. OrderByDescending (orderByRole)
. Skip (pageSize * (pageIndex-1 ))
. Take (pageSize). AsQueryable ();
}
Else
{
Temp = temp. OrderBy (orderByRole)
. Skip (pageSize * (pageIndex-1 ))
. Take (pageSize). AsQueryable ();
}
Return temp;
}
# Endregion
}
At this point, I thought I had finished writing my database access layer, and then I could write something on the business logic layer. Actually, it is not. Think about it. If you want to change the database, or change to ef or ado.net. If we use the old one, we need to replace each layer of the entire project, which greatly increases the workload. Here we can do something about it, the data access layer is abstracted to another layer, which requires an interface.
IDAL. IBaseRepository <T> let's look at our bll layer. If there is no interface, we write the dal directly. xxrepository = new xxrepository (); As I mentioned earlier, the maintainability is greatly reduced .. we can write this now
IDAL. xxrepository = new xxrepository (). in this way, when we replace the DAL layer, the root of the BLL layer does not need to care about how you implement it. this is very important. the interface is equivalent to a contract, which limits the functions you must implement. If you want to add a function, you can add it directly to the interface. The interface must be part of the interface, as shown in the code above, the base class requires an interface, and the subclass also needs. in this way, a database interface layer is abstracted.
Abstract Factory and simple factory
We can also abstract the business layer and database access layer. here we need to use the factory-in fact, it is very simple. The dal layer class obtained from the factory class and the IDAL interface is returned.Copy codeThe Code is as follows: public static class ShopDaoFactory
{
Public static IUserInfoRepository UserInfoRepository
{
Get {return new UserInfoRepository ();}
}
Public static IRoleRepository RoleRepository
{
Get {return new RoleRepository ();}
}
}
The business layer does not need to care about how to implement the interface when it obtains the interface. This is a layer of abstraction. Of course, you can also use the abstract factory to implement it using reflection, configuration, and cache, however, in general, it is enough for a simple factory. This is equivalent to a database access layer entry.
Base class and subclass of the business logic layer
When we have more entity models, if we do not have a base class, we need to write a bunch of repetitive things, now we need to put these repetitive things into the base class for implementation. Like the Dal layer, we define a base class, but we will encounter a problem at the BLL layer, IDAL. IBaseRepository <T> how to obtain the interface obtained from the factory ...... think about it ..... our subclass can know the interface we need ------ we can make a hand and feet, let the parent class be an abstract class, define an abstract method, and then let the subclass rewrite and modify the method, and it is called in the constructor. Because we must use this interface, it must be in the constructor.Copy codeThe Code is as follows: public abstract class BaseService <T>: IBLL. IBaseService <T> where T: class, new ()
{
Public BaseService ()
{
GetInstance ();
}
Protected IDAL. IDbSession _ DbSession = DbSeesionFactory. GetSession ();
Protected IDAL. IBaseRepository <T> CurrentRepository {get; set ;}
Public abstract void GetInstance ();
Public IQueryable <T> GetEntities (Func <T, bool> lambdaWhere)
{
// _ DbSession. SavaChanges ();
Return CurrentRepository. GetEntities (lambdaWhere );
}
Public bool DeleteEntity (T entity)
{
CurrentRepository. DeleteEntity (entity );
Return _ DbSession. SaveChanges ()> 0;
}
Public bool UpdateEntity (T entity)
{
CurrentRepository. UpdateEntity (entity );
Return _ DbSession. SaveChanges ()> 0;
}
Public T AddEntity (T entity)
{
Var en = CurrentRepository. AddEntity (entity );
_ DbSession. SaveChanges ();
Return en;
}
Public IQueryable <T> GetEntitiesByPageIndex <TS> (int pageIndex, int pageSize, out int totalCount, Func <T, bool> lambdaWhere, Func <T, TS> orderByRole, bool descending)
{
Return CurrentRepository. GetEntitiesByPageIndex (pageIndex, pageSize, out totalCount, lambdaWhere, orderByRole,
Descending );
}
}
}
Other business layers also need interfaces to abstract a layer as the constraint, so that the ui Layer does not need to care about how your business layer is implemented...
Another method is to implement DBSession for database entry.
Let's first look at a class. dbsession has an attribute, which is an interface, corresponding to the implementation class of this interface, two methods SaveChanges (), and exesql (EF uses 5.0 + ), it returns the savechange () of the current EF thread context and the return value of the executed SQL statement. How can we ensure that there is only one EF context in the current process? Let's look at another class.Copy codeThe Code is as follows: public partial class DbSession: IDAL. IDbSession
{
# Region code generator generation
// Public IDAL. IRoleRepository RoleRepository
//{
// Get {return new RoleRepository ();}
//}
// Public IDAL. IUserInfoRepository UserInfoRepository
//{
// Get {return new UserInfoRepository ();}
//}
# Endregion
Public int SaveChanges ()
{
Return EFContentFactory. GetCurrentContext (). SaveChanges ();
}
Public int ExcuteSql (string strSql, System. Data. Objects. ObjectParameter [] parameters)
{
Return EFContentFactory. GetCurrentContext (). Database. ExecuteSqlCommand (strSql, parameters );
}
}
Public class EFContentFactory
{
Public static DbContext GetCurrentContext ()
{
DbContext obj = CallContext. GetData ("DbContext") as DbContext;
If (obj = null)
{
Obj = new Model. DataContainer ();
CallContext. SetData ("DbContext", obj );
}
Return obj;
}
}
CallContext is a special collection object similar to the local storage area of the thread for method calls, and provides a data slot that is unique to each logic execution thread. The data slot is not shared between call contexts on other logic threads. This is a piece of text taken from msdn. It has several methods. Here we use setdata and getdata, to ensure that the context thread is unique. Similarly, we make it interface-based --Copy codeThe Code is as follows: public class DbSeesionFactory
{
/// <Summary>
/// Ensure that the dbsession in the thread is unique
/// </Summary>
/// <Returns> </returns>
Public static IDAL. IDbSession GetSession ()
{
IDAL. IDbSession _ dbSession = CallContext. GetData ("DbSession") as IDbSession;
If (_ dbSession = null)
{
_ DbSession = new DbSession ();
CallContext. SetData ("DbSession", _ dbSession );
}
Return _ dbSession;
}
}
This method is implemented when the subclass Rewriting Method of the business layer is used. Add a base class: protected IDAL. IDbSession _ DbSession = DbSeesionFactory. GetSession ();Copy codeThe Code is as follows: public partial class ActionInfoService: BaseService <ActionInfo>, IBLL. IActionInfoService
{
Public override void GetInstance ()
{
CurrentRepository = _ DbSession. ActionInfoRepository;
}
}
Public partial class R_UserInfo_ActionInfoService: BaseService <R_UserInfo_ActionInfo>, IBLL. IR_UserInfo_ActionInfoService
{
Public override void GetInstance ()
{
CurrentRepository = _ DbSession. R_UserInfo_ActionInfoRepository;
}
}
Public partial class RoleService: BaseService <Role>, IBLL. IRoleService
{
Public override void GetInstance ()
{
CurrentRepository = _ DbSession. RoleRepository;
}
}
Why? When we use EF, for example, if we need to operate multiple tables in a method, we need to constantly use the context. This will help us with a lot of things and finally directly use the _ dbsession. savechange (). batch deletion and modification operations can be performed. for details, I have made a batch Delete today.Copy codeThe Code is as follows: public int DeleteUsers (List <int> list)
{
Foreach (var I in list)
{
_ DbSession. UserInfoRepository. DeleteEntity (new UserInfo () {ID = I });
}
Return _ DbSession. SaveChanges ();
}
I am so sleepy. I have learned a lot from my summary of the things I 've learned over the past few days. Although I am not very familiar with some of the things in it, I 've learned from them and shared it with the university ~