根据列属性值获取属性值

时间:2012-01-25 08:34:55

标签: linq c#-4.0 columnattribute

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中某个属性的Column属性之一的值相同。所以我必须在myUserModel中搜索列atribute(Name)并获取相应的属性值并将其分配给'FieldValue'。如果我在myUserModel中找不到值,我可以将'FieldValue'设置为“NA”

当我知道属性名称时,获取属性的列属性(Name)值的一种方法如下所示。

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中搜索具有Column属性(Name)作为first_name的属性。如果它存在,我必须将它的值设置为'FieldValue'。否则将'FieldValue'设置为“NA”。

1 个答案:

答案 0 :(得分:2)

如果你想获取一个属性的值,你只知道其中一个ColumnAttribute属性的Name属性,你可以这样做:

// 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! :-)
}

这就是你想要的吗?