我正在编写一个函数来更新表中的行(SQLite)。有一次,我只需要更新该行的某些列。
我的视频类(和表)具有以下属性(和列): 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);
}
}
}
那我该如何阅读&#34; foreach&#34;新项目的每个属性,如果该属性不为空,则更新为旧项目的属性?
答案 0 :(得分: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);
}
答案 1 :(得分:0)
您可以使用反射来获取视频项目的所有属性(请查看http://msdn.microsoft.com/en-us/library/kyaxdd3x(v=vs.110).aspx),但解决方案会很慢而且很混乱。只需为每个属性编写测试和更新代码。
答案 2 :(得分: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
}