使用LINQ在运行时从数据库获取数据
问题描述:
我希望能够编写和更新我的数据库,将对象发送到我的服务,然后让服务动态决定要写入或更新到数据库的对象类型。使用LINQ在运行时从数据库获取数据
这是静态地做这件事的时候(更新的例子),我做什么
switch ((string)property.GetValue(oLinq, null))
{
case "news":
t_news oNews = (t_news)oLinq;
List<t_news> newsList = (from n in oDB.t_news where n.ID.Equals(oNews.ID) select n).ToList();
t_news oNe = newsList[0];
i = 0;
foreach (System.Reflection.PropertyInfo p in oNews.GetType().GetProperties().ToList())
{
if (p.GetValue(oNews, null) != null)
{
typeof(t_news).GetProperties().ToList()[i].SetValue(oNe, p.GetValue(oNews, null), null);
}
i++;
}
oNe.dLastUpdate = DateTime.Now;
oDB.SubmitChanges();
oLinq = (object)oNews;
break;
return oLinq;
ODB是我的DataContext。 oLinq只是一个包含我想要更新的数据的对象。 它包含一个字段,我在其中指定需要更新哪种表。 我使用开关箱来确定指定该表。 我现在有4种不同的情况,在这种情况下我几乎完全相同。
但我希望能够动态地做到这一点,所以我不必重写所有这些代码4次,并且能够在将来添加新表格。
这就是我想:
List<string> alsTableNames = (from tables in oDB.Mapping.GetTables() select tables.TableName).ToList();
foreach (string sTableName in alsTableNames)
{
if (String.Compare(sTableName.Substring(6), (string)property.GetValue(oLinq, null)) == 0)
{
string sBasicType = sTableName.Replace("dbo.", "");
string sType = "RegisterService." + sBasicType;
Type tType = Type.GetType(sType);
oLinq = Convert.ChangeType(oLinq, tType);
该工程的oLinq对象转换为类型我想要的。 但是,不起作用的是从数据库中获取数据以将其替换为新数据。 基本上,我需要一种方法来做到这一点,以动态方式:
List<t_news> newsList = (from n in oDB.t_news where n.ID.Equals(oNews.ID) select n).ToList();
t_news oNe = newsList[0];
喜欢的东西:
List<//type of the table I want> list = (from t in //table where t.//firstproperty.Equals(oLinq.getType().getProperties().toList()[0]) select t.ToList();
object oNewObj = list[0];
什么想法?
答
你看过使用Dynamic LINQ?
使用它,你可以做一些与此类似:
// Use reflection to figure out what type of entity you need to update
var tYourEntityType = /* your code to get the type of the object you will be working with */;
// Get the entity you need to update querying based on a dynamic where clause
string propetyNameToSeach = "firstproperty"; // set this dynamically to the name of the property
string propertyValueToCompare = "5"; // set this dynamically to the value you want to compare to
var entityToUpdate = youDataContext.GetTable<tYourEntityType>().Where(propetyNameToSeach + " = " + propertyValueToCompare).FirstOrDefault();
C#泛型的列表其中T是表的类型你想 –
FiveTools
2012-04-18 15:27:34
列表类型是不是一个真正的问题,因为我只想要一个对象从那个列表(与我发送的对象具有相同ID的那个oLinq对象) 因此,我可以将列表制作为列表