如何从MVC中的动态表中检索数据

时间:2019-06-12 09:34:28

标签: c# asp.net-mvc entity-framework linq

我正在为我的Android应用程序编写新的api调用,我想从动态表中检索数据,这意味着当用户从Andriod中选择“ A”按钮时,我想从“ A”表中检索数据,如果是“ B”单击,从“ B”表中检索数据。有人帮助我找到可能的解决方案。

我想用来自实体。JBCTNRITEM(表名)的变量替换为“ JBCTNRITEM”(表名)

    var query = (from jbct in entities.JBCTNRITEMs
                 where jbid.Contains(jbct.jbid.ToString()) && boxid.Contains(jbct.TrackingNo.ToString())
                 select jbct).ToArray();
    int id = 0;
    if (query.Length > 0)
    {
        id = (query[0].id);
    }
    return id;

以下是两种不同的可能性

if (module.ToLower() == "module-a") 
{
      var imageinfo = (from jb in entities.TableA.AsEnumerable() 
                       where scanID.Contains(jb.aid.ToString()) 
                       select jb).ToArray(); 
       InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "AIMAGE"); 
}
else if (module.ToLower() == "module-b") 
{
    var imageinfo = (from jb in entities.TableB.AsEnumerable() 
                     where scanID.Contains(jb.bid.ToString()) 
                     select jb).ToArray(); 
    InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "BIMAGE"); 
}

2 个答案:

答案 0 :(得分:1)

在这里,query存储您要选择的内容。只要您尝试选择相同类型或相同匿名类型,它就会起作用。

这是一个简单的例子:

class Test1
{
     public int ID { get; set; }
     public string Name { get; set; }
}

class Test2
{
      public int ID { get; set; }
      public string Name { get; set; }
}

var test1Lst = new List<Test1>
{
      new Test1() { ID = 1, Name = "Jitendra" },
      new Test1() { ID = 2, Name = "Jahnavi" }
};

var test2Lst = new List<Test2>
{
      new Test2() { ID = 1, Name = "Aaditri" },
      new Test2() { ID = 2, Name = "Pankaj" }
};

var test = false;
var query = test ? (from t in test1Lst select new { ID = t.ID, Name = t.Name }) : (from t in test2Lst select new { ID = t.ID, Name = t.Name });

// Put whatever condition you want to put here   
query = query.Where(x => x.ID == 1);

foreach(var t1 in query)
{
      Console.WriteLine(t1.ID + " " + t1.Name);
}

答案 1 :(得分:0)

我想在这种情况下,我建议使用通用方法:

private T GetMeTheFirstEntry<T>(Expression<Func<T, bool>> filter) where T : class
{
    return entities.GetTable<T>().FirstOrDefault(filter);
}

GetTable将允许您互换tableA和tableB。您可以通过以下方式调用它:

TableA tableA_entity = GetMeTheFirstEntry<TableA>(jb => scanID.Contains(jb.aid.ToString()));
TableB tableB_entity = GetMeTheFirstEntry<TableB>(jb => scanID.Contains(jb.bid.ToString()));

如果过滤成功,则检索到的对象将不会为空,您可以使用它:

int a_id = tableA_entity.aid;
相关问题