【问题标题】:Getting property value based on its column attribute value根据其列属性值获取属性值
【发布时间】:2012-01-27 18:29:31
【问题描述】:
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中搜索列属性(名称)并获取相应的属性值并将其分配给'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 中搜索以 Column 属性(名称)作为 first_name 的属性。如果它存在,我必须将它的值设置为“FieldValue”。否则将“FieldValue”设置为“NA”。

【问题讨论】:

    标签: linq c#-4.0 columnattribute


    【解决方案1】:

    如果你想获取一个属性的值,而你只知道它的 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! :-)
    }
    

    这是你想要的吗?

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多