myModel1Field.FieldAlias文本将与其中一个属性的Column属性的值相同myUserModel。所以我必须在myUserModel中搜索列的name(name),并获取相应的属性值并将其赋给'FieldValue'。如果我在myUserModel中找不到该值,我可以将FieldValue设置为NA
myModel1Field.FieldAlias text will be same as value of one of the Column attribute of one of the property in myUserModel. So I have to search for the column atribute(Name) in myUserModel and get the corresponding property values and assign it to 'FieldValue'. If I can't find the value in myUserModel I can set 'FieldValue' as "NA"
一种获取属性的列属性
myUserModel.GetType().GetProperty("FirstName").GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).Cast<System.Data.Linq.Mapping.ColumnAttribute>().Single().Name但在我的例子中属性名称不会被知道。我必须找到基于myModel1Field.FieldAlias值的属性。如何去做这个。请建议。
But in my case Property name will not be known. I have to find the property based on the myModel1Field.FieldAlias value. How to go about this. Please suggest.
MyUserModel及其属性之一
MyUserModel with one of it's properties
public class MyUserModel { [Column(Name = "first_name", DbType = "varchar")] public string FirstName { get; set; } }
现在如果myModel1Field。 FieldAlias是'first_name',那么我必须在MyUserModel中搜索具有Column属性(Name)作为first_name的属性。如果它存在,我必须设置它的值为'FieldValue'。 Else将FieldValue设置为NA。
Now if myModel1Field.FieldAlias is 'first_name' then I have to search in MyUserModel for a property with Column attribute(Name) as first_name. If it exists i have to set it's value to 'FieldValue'. Else set 'FieldValue' as "NA".
推荐答案如果要获取属性的值,您可以做的一个ColumnAttribute属性的Name属性如下:
If you want to get the value of a property and you only know the Name property of one of the ColumnAttribute attributes on it what you can do is this:
// 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! :-) }这是你想要的吗?
更多推荐
根据其列属性值获取属性值
发布评论