1

Normally I use stored procedures / work in SQL so apologies if I get the terminology slightly off here..

I have a database, with 3 seperate tables, and I need to search multiple fields in each of the 3 tables.

Im sure that I am not doing this the mose effective way, initially I am trying to do it in simple seteps to understand it.

I have the following;

    var foo1 = entities.table1.Where(a => a.bodyText.Contains(searchString) || a.pageTitle.Contains(searchString));
    var foo2 = entities.table2.Where(b => b.newsArticle.Contains(searchString) || b.newsArticle.Contains(searchString));
    var foo3 = entities.table3.Where(c => c.ImageDescriptionContains(searchString));

I need to combine all these results into a single repeater for display.

At this point all 3 sets of data are in seperate, unique collections of anonymous data. So whats the best way of converting these into a single coherent bindable source?

I was thinking of itereating through each list in turn, pulling out the fields I need to display and putting them in a new class, then binding a lsit of these classes to the repeater.

But it all seems a bit clunky to me.

Is there a way of doing the search across all 3 tables in one go, and returning just the fields I need from each table, with a common name (i.e. in SQL I could write

    select b.newsArticle as myText, 

or

    select newsArticle, '' 

to return the news article and an empty string).

4

2 回答 2

1

要一次性获得所有结果,您需要定义一个公共类,所有三个查询都将使用该类来存储结果。这个类也可以是匿名的,但为了清楚起见,我会命名它。

class Data
{
    public string Text{ get; set;}
}

现在,在您的代码中,您Data将从数据库中获取实例,您可以使用Union

using( var entities = new YourDataContext)
{
    var foo1 = entities.table1
                       .Where(a => a.bodyText.Contains(searchString) || 
                                   a.pageTitle.Contains(searchString))
                       .Select(a => new Data{ Text = a.bodyText});
    var foo2 = entities.table2
                       .Where(b => b.newsArticle.Contains(searchString) || 
                                   b.newsArticle.Contains(searchString))
                       .Select(b => new Data{ Text = b.newsArticle});
    var foo3 = entities.table3
                       .Where(c => c.ImageDescription.Contains(searchString))
                       .Select(c => new Data{ Text = c.ImageDescription});
    return foo1.Union(foo2).Union(foo3);
}
于 2012-05-18T09:49:43.217 回答
1

这将结合:

var foos = foo1.ToList();
foos.AddRange(foo2);
foos.AddRange(foo3);

为了得到你想要的:

var myExtractedValues = foos.Select(x => new { 
         Article = !string.IsNullOrEmpty(x.newsArticle)) 
                           ? x.newsArticle 
                           : string.Empty});

我在这里使用了匿名类型,但您可以将新的 {} 替换为您自己的类型。

我反转 IsNullOrEmpty 上的运算符,但这只是个人喜好(我更喜欢如何读取。)

于 2012-05-17T16:39:06.660 回答