首页 > 代码库 > 关于在EF中通用方法

关于在EF中通用方法

在EF中有时需要用到一些通用类,在后端模型和前端模型在某些场合需要模型分离,

例如数据模型和试图模型中用到的增删改功能

  public class DBHelper<V, T>
        where V : class ,new()
        where T : class ,new()
    {


        public Result Update(V Entity)
        {
            using (var db = new DbContext())
            {

                 //此处模型转换
                var model = EntityOperation<T>.Conversion(Entity);
                db.Set<T>().Attach(model);
                db.Entry<T>(model).State = System.Data.Entity.EntityState.Modified;
                return this.SaveChanges(db);
            }
        }
        public Result UpdateForT(T Entity)
        {
            using (var db = new DbContext())
            {
                db.Set<T>().Attach(Entity);
                return this.SaveChanges(db);
            }
        }
    }

转换模型方法

   /// <summary>
        /// 转换一个字段相同的实体
        /// </summary>
        /// <param name="InObject">有值需要转换的实体</param>
        /// <returns>返回转好的 TEntity</returns>
        public static TEntity Conversion(object InObject)
        {
            var _temp = InObject.GetType().GetProperties();
            TEntity entity = new TEntity();
            foreach (var item in _temp)
            {
                object ovj = item.GetValue(InObject, null);
                if (ovj != null)
                {
                    var _obj = entity.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower() == item.Name.ToLower());
                    if (_obj != null)
                        _obj.SetValue(entity, ovj);
                }
            }
            return entity;
        }

关于在EF中通用方法