Scenario:
Use a ORM framework to work with your database.Solution:
NHibernate is an open-source ORM framework, which is persistence layer for the .Net based on Object-Relational Mapping Technique. It creates a "virtual representation" of database objects within the code.
NET Framework. It handles persisting plain .NET objects to and from an underlying relational database. Given an XML description of your entities and relationships, NHibernate automatically generates SQL for loading and storing the objects.
Object Relational Mapping (ORM) is a technique used in creating a "bridge" between object-oriented programs and, in most cases, relational databases. It solves the issues like DB does not have inheritance and the structure is diffrent between DB and classes.
NHibernate, persists the object into the relation database and can do CRUD operations, you dont have to write SQL queries, the data access logic can be contained in the application.
1. The XML mapping file, which can be done in the code as well.
2. Configuration file
3. POCO
They need to have atleast one id property
All properties need to be marked Virtual
//Construct a Session Factory var sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008.ConnectionString(sqlConnection)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyContext>()) .BuildSessionFactory(); //start a session and save data/ Flush mode could be Manual, Automatic and commit time using (var session = NHibernateHelper.OpenSession() Session.FlushMode = FlushMode.Manual) { using (var transaction = session.BeginTransaction()) { var user = new User { FirstName = "Ram", LastName = "Mangal" }; session.Save(customer); session.Flush(); transaction.Commit(); session.Close(); }//Mappingclass UserMap : ClassMap<User> { public UserMap() { Id(x => x.Id); Map(x => x.FirstName); Map(x => x.LastName); Table("User"); } //load data using (ISession session = NHibertnateSession.OpenSession()) { using (var tx = session.BeginTransaction()) { /*** Using Query ***/ var users = session.Query<User>().ToList(); foreach (var user in users) { //read user data } tx.Commit(); } }
No comments:
Post a Comment