1. 程式人生 > 實用技巧 >使用C#反射,實現檢視模型到資料庫模型的屬性轉換

使用C#反射,實現檢視模型到資料庫模型的屬性轉換

當需要操作某個型別集合中的每個屬性時,在前端我們不容易拿得到集合中的每個實體的屬性。為了解決這種問題,我們可以使用反射。

1.一張表有N個物件的時候,我們操作其中的一種屬性。例如在資料庫中存在學生表(Student)中,只要操作學生的姓名(StuName列)

StuID StuName StuClass StuAge
1   Zhang ClassOne 8
2 Zhou ClassTow 9
3 Sun ClassThree 7

2.而我想要在頁面中如下展示資料,並且姓名為可編輯:

學生: Zhang
學生: Zhou
學生: Sun

3.此時,我們可以將StuName列下的所有值封裝到一個類中:

public class Name
{
  public string Zhang{get;set;}   public string Zhou{get;set;}   public string Sun{get;set;} }

[HttpGet]
public ActionResult Index()
{
  List<Student> lists = _db.Student.toList(); //拿到資料庫中所有的Student物件
  Name names = new Name();

   PropertyInfo[] Pros = typeof(Name).GetProperties();
   

   foreach (var pro in Pros)
   {
     string proValue = GetOptions(lists, pro.Name);
     pro.SetValue(names, proValue);
   }

   return View(names);

}

//得到源資料的StuName
private string GetOptions(List<Student> source ,string key)
{
  var find = source.FirstOrDefault(o => o.StuName == key);
  if (find == null)
  {
    throw new Exception("key值不存在");
  }
  return find.StuName;
}


//寫入源資料的StuName
private void SetOptions(List<Student> source, string key, string value)
{
  var find = source.FirstOrDefault(o => o.OptionID == key);
  if (find != null)
  {
    find.StuName = value;
  }
}