Should I use generics to simplify my DAL?

前端 未结 3 1105
Happy的楠姐
Happy的楠姐 2021-01-24 12:33

I\'m new to NHibernate and not very good at C#, but I\'m learning. I have a DataProvider class which provides data for my application using NHibernate 3. It\'s stru

3条回答
  •  醉酒成梦
    2021-01-24 13:10

    Your data provider class doesn't necessarily need to be generic - you can just make the AddEntity method itself generic. Then you instantiate a DataProvider instance, and call (for example) its AddEntity method. Your class would look like this:

    public class DataProvider
    {
        public int AddEntity(TEntity entity)
        {
            using (ITransaction tx = _session.BeginTransaction())
            {
                try
                {
                    int newId = (int)_session.Save(entity);
                    _session.Flush();
                    tx.Commit();
                    return newId;
                }
                catch (NHibernate.HibernateException)
                {
                    tx.Rollback();
                    throw;
                }
            }
        }    
    }
    

提交回复
热议问题