4
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のプロパティの1つのColumn属性の1つの値と同じになります。したがって、myUserModelで列atribute(Name)を検索し、対応するプロパティ値を取得して、それを「FieldValue」に割り当てる必要があります。myUserModelに値が見つからない場合は、「FieldValue」を「NA」に設定できます。

プロパティの列属性(名前)値を取得する1つの方法は、プロパティ名がわかっている場合は次のとおりです。

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

しかし、私の場合、プロパティ名はわかりません。myModel1Field.FieldAlias値に基づいてプロパティを見つける必要があります。これについて行く方法。提案してください。

そのプロパティの1つを持つ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」に設定します。

4

1 に答える 1

4

プロパティの値を取得したいが、そのプロパティの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! :-)
}

それはあなたが望むものですか?

于 2012-01-25T12:50:51.597 に答える