C # primary key acquired by the reflection or the name of the entity class value acquired entity classes

 

// Get the primary key PropertyInfo 
PropertyInfo pkProp = typeof (T) .GetProperties () the Where (P => p.GetCustomAttributes (. Typeof (KeyAttribute), to false ) .Length> 0 ) .FirstOrDefault ();
 // primary key name 
var the keyName = pkProp.Name;
 // value of the primary key of the entity class 
 var keyId = pkProp.GetValue (Model) .ToString ();

E.g:

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 };
        }

 

Guess you like

Origin www.cnblogs.com/firstcsharp/p/11114677.html