2014-10-09 78 views
0

我在写一个函数来更新表(SQLite)中的一行。有一次我只需要更新该行的某些列。使用foreach属性的类

我的视频类(和表)具有以下属性(和列): Id,Name,Lyric,Cover,Gendre,Url。 (他们所有的字符串)

现在,例如,我需要更新的歌词和表1排的掩护下,我使用这个代码:

string id = // still keep the old id, this's the PK of table; 
string lyric = //get new lyric; 
string cover = // get new cover; 
Video item = new Video(){Id = id, Lyric = lyric, Cover = cover}; 
SQLiteAccess.EditVideoInfo(item); 

这里的EditVideoInfo

public static void EditVideoInfo(Video item) 
    { 
     var conn = new SQLiteConnection(mypath); 
     using (conn) 
     { 
      var list = conn.Query<Video>("SELECT * FROM Video WHERE Id =?", item.Id); 
      if (list.Count >0) 
      { 
       var editItem = list.First(); // -> Get the item need to updated 
       /// Here's where I'm stuck 
       conn.Update(editItem);      
      } 
     } 
    } 

那么如何读取“foreach”新项目的每个属性并更新为旧项目的属性(如果该属性不为null)?

回答

1

像下面的东西。

var props = typeof(Video).GetProperties(BindingFlags.Instance|BindingFlags.Public|BindingFlags.GetProperty|BindingFlags.SetProperty); 

foreach (var prop in props) { 
    var propVal = prop.GetValue(item, null); 
    if (propVal != null) 
     prop.SetValue(editItem, propVal, null); 
} 
+0

它的作品完美地重复!非常感谢你:D – user3448806 2014-10-09 12:00:34

0

我的第一个做到这一点的方法是创建一个dictionary

Dictionary<string, string> _properties = new Dictionary<string, string>(); 
_properties["id"] = "myID" 
_properties["lyric"] = "some other string" 

,然后你可以通过它在foreach

foreach (var prop in _properties) 
{ 
    // do something with prop 
}