2010-07-15 44 views
1

如何:您不想手動編寫代碼寫入ColumnA,ColumnB等,那麼您可以使用反射來寫入實體的相應屬性? 您可以創建此類的新實例及其屬性值。這些屬性值被映射到SQL數據庫表中的列。然後將該對象傳遞給由LINQ to SQL生成的DataContext類,以向數據庫中的表添加新行。如何使用反射寫入實體的相應屬性?

所以,你會做這樣的事情:


For a database table with columns "ColumnA", "ColumnB" and "ColumnC" 

var myEntity = new EntityObject { ColumnA = "valueA", ColumnB = "valueB", "ColumnC" = "valueC" }; 
DataContext.InsertOnSubmit(myEntity); 
DataContext.SubmitChanges(); 

這將插入新行與指定的列值的數據庫。

現在,如果你不想手動編寫代碼來寫ColumnA,ColumnB,等等,那麼你可以使用反射來寫對實體相應的屬性:

例如,實體實例「 myEntity':


var properties = myEntity.GetType().GetProperties(); 

foreach (string ky in ld.Keys) 
{ 
    var matchingProperty = properties.Where(p => p.Name.Equals(ky)).FirstOrDefault(); 
    if (matchingProperty != null) 
    { 
     matchingProperty.SetValue(myEntity, ld[ky], null); 
    } 
} 

我嘗試這個,但我不能。你怎麼能做到的?

+0

那麼,發生了什麼事,當你* *沒有嘗試? (順便說一下,您可能希望使用Type.GetProperty來更容易地獲取屬性,或者遍歷所有屬性並查看它們是否在地圖中。) – 2010-07-15 06:55:08

回答

1

檢查這篇文章:LINQ到SQL:All common operations (Insert, Update, Delete, Get) in one base class 以下可以幫助你:

protected virtual void Update(T entity, Expression<Func<T, bool>> query) 
{ 
    using (DC db = new DC()) 
    { 
    object propertyValue = null; 
     T entityFromDB = db.GetTable<T>().Where(query).SingleOrDefault(); 
      if (null == entityFromDB) 
      throw new NullReferenceException("Query Supplied to " + 
        "Get entity from DB is invalid, NULL value returned"); 
     PropertyInfo[] properties = entityFromDB.GetType().GetProperties(); 
     foreach (PropertyInfo property in properties) 
     { 
      propertyValue = null; 
       if (null != property.GetSetMethod()) 
       { 
        PropertyInfo entityProperty = 
         entity.GetType().GetProperty(property.Name); 
        if (entityProperty.PropertyType.BaseType == 
         Type.GetType("System.ValueType")|| 
         entityProperty.PropertyType == 
         Type.GetType("System.String")) 

         propertyValue = 
         entity.GetType().GetProperty(property.Name).GetValue(entity, null); 
        if (null != propertyValue) 
         property.SetValue(entityFromDB, propertyValue, null); 
       } 
      } 
      db.SubmitChanges(); 
     } 
    }