简体   繁体   中英

Querying data from multiple disjoint tables (EF6)

I am currently trying to automate a search task. Basically, what I have are multiple tables like this:

  • TableA with columns: Id, PartNumber, Value, R
  • TableB with columns: Id, PartNumber, Value, C
  • TableC with columns: Id, PartNumber, Value, X
  • ...

Basically multiple very similar tables. What I am now trying to do is, is to search for a text string in the fields "PartNumber" and "Value". I don't mind if it occurs in any of the columns R,C,X.

Is there a way to

  1. Query which table names exist
  2. Then execute the very same query on each of those tables
  3. Concatenate the results (I don't mind if the type differs in the list or if it becomes a new type)

In case a new table is added, it should only be added to the context and then get automatically searched.

Assuming you have

class TableA
{
    public int Id { get; set; }
    public string PartNumber { get; set; }
    public string Value { get; set; }
    public int R { get; set; }
}

class TableB
{
    public int Id { get; set; }
    public string PartNumber { get; set; }
    public string Value { get; set; }
    public int C { get; set; }
}

class TableC
{
    public int Id { get; set; }
    public string PartNumber { get; set; }
    public string Value { get; set; }
    public int X { get; set; }
}

List<TableA> tableAs = new List<TableA>();
List<TableB> tableBs = new List<TableB>();
List<TableC> tableCs = new List<TableC>();

one of the ways you can query it is like this:

var result = tableAs.Select(e => (e.PartNumber, e.Value))
    .Union(tableBs.Select(e => (e.PartNumber, e.Value)))
    .Union(tableCs.Select(e => (e.PartNumber, e.Value)))
    .Where(e => e.PartNumber.Contains("something") || e.Value.Contains("something else"))
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM