zoukankan      html  css  js  c++  java
  • C#利用反射获取实体类的主键名称或者获取实体类的值

    //获取主键的 PropertyInfo
    PropertyInfo pkProp = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length >0).FirstOrDefault();
    //主键名称
    var keyName=pkProp.Name;
    //实体类中主键的值
     var keyId = pkProp.GetValue(model).ToString();

    例如:

    public WorkIDStatusViewModel GetWorkIDStatusEntity<T>(string resourcesCode, IEnumerable<t_Work> work, T model)
            {
                PropertyInfo pkProp = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Length >0).FirstOrDefault();
                var resourcesId = pkProp.GetValue(model).ToString();
    
                var entity = work.Where(r => r.ResourcesCode == resourcesCode && r.ResourcesId == resourcesId).OrderByDescending(r => r.CreateDate).Select(s => new WorkIDStatusViewModel { WorkId = s.WorkId, Status = s.Status }).FirstOrDefault();
                if (entity != null)
                    return new WorkIDStatusViewModel { WorkId = entity.WorkId, Status = entity.Status };
                else
                    return new WorkIDStatusViewModel { WorkId = "", Status = -1 };
            }
  • 相关阅读:
    RedMine 1.3.3 安装攻略
    .net 4.0 framework 安装时发生严重错误
    MYSQL安装配置
    接口隔离ISP
    依赖倒置DIP
    VS2010添加WP模板
    VS2012尝鲜
    OCP开放闭合
    单一职责
    里氏替换
  • 原文地址:https://www.cnblogs.com/firstcsharp/p/11114677.html
Copyright © 2011-2022 走看看