2012-01-25 95 views
3
List<MyModel1> myModel1 = new List<MyModel1>();      
MyUserModel myUserModel = new MyUserModel();      
List<MyModel2> myModel2 = new List<MyModel1>(); 
myModel1 = m_Service1.GetMyModelFields(); 
myUserModel = m_Service2.GetMyUserDetails(); 
myModel2 = (from myModel1Field in myModel1       
      select new MyModel2 { FieldCaption = myModel1Field.FieldAlias, 
      FieldValue = "" }).ToList<MyModel2>(); 

myModel1Field.FieldAlias文本将相同myUserModel属性之一的列属性的一个值。所以我必须在myUserModel中搜索列属性(Name)并获取相应的属性值并将其赋值给'FieldValue'。如果我在myUserModel中找不到值,我可以将“FieldValue”设置为“NA”获得属性值

获取属性的列属性(名称)值的一种方法是当我知道属性名称时。

myUserModel.GetType().GetProperty("FirstName").GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).Cast<System.Data.Linq.Mapping.ColumnAttribute>().Single().Name 

但在我的情况下属性名称将不知道。我必须根据myModel1Field.FieldAlias值找到属性。如何去做这件事。请建议。

MyUserModel与它的一个特性

public class MyUserModel { 
[Column(Name = "first_name", DbType = "varchar")] 
public string FirstName { get; set; } 
} 

现在,如果myModel1Field.FieldAlias是“FIRST_NAME”,那么我在MyUserModel以搜索与列属性(名称)作为FIRST_NAME的属性。如果存在,我必须将它的值设置为'FieldValue'。否则将“FieldValue”设置为“NA”。

回答

2

如果你想获得一个属性的值,你只知道ColumnAttribute之一的名称属性的属性就可以了,你可以做的是这样的:

// Let's say you have the user model like so: 
MyUserModel myUserModel = new MyUserModel { FirstName = "A", LastName = "B"}; 

// And then you want the value of the property that has the Column attribute Name "first_name" 
string searchName = "first_name";  

// Using some lambda you can do this (I do not know how to do this in LINQ syntax, sorry) 
object propertyValue = typeof (MyUserModel).GetProperties() 
      .Where(p => 
         { 
          var attrib = (ColumnAttribute)p 
           .GetCustomAttributes(typeof (ColumnAttribute), false) 
           .SingleOrDefault(); 
          return (attrib != null && 
            attrib.Name.Equals(searchName)); 
         }) 
      .Select(p => p.GetValue(myUserModel, null)) 
      .FirstOrDefault(); 

if(propertyValue != null) 
{ 
    // Do whatever you want with the string "A" here - I suggest casting it to string! :-) 
} 

这是你想要的吗?