使用LINQ在运行时从数据库获取数据

时间:2012-04-18 15:25:24

标签: c# 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只是一个包含我想要更新的数据的对象。 它包含一个字段,我在其中指定需要更新的表类型。 我使用switch case来确定指定该表。 我现在有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];

任何想法?

1 个答案:

答案 0 :(得分: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();
相关问题