zoukankan      html  css  js  c++  java
  • 关于在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;
            }

  • 相关阅读:
    hdu 5170 GTY's math problem(水,,数学,,)
    hdu 5178 pairs(BC第一题,,方法不止一种,,我用lower_bound那种。。。)
    hdu 5179 beautiful number(构造,,,,)
    cf12E Start of the season(构造,,,)
    cf12D Ball(MAP,排序,贪心思想)
    cf 12C Fruits(贪心【简单数学】)
    cf 12B Correct Solution?(贪心)
    hdu 5171 GTY's birthday gift(数学,矩阵快速幂)
    hdu 5172 GTY's gay friends(线段树最值)
    cf 11D A Simple Task(状压DP)
  • 原文地址:https://www.cnblogs.com/drwu2009/p/4096435.html
Copyright © 2011-2022 走看看