【问题标题】:Linq search query multiple tablesLinq搜索查询多个表
【发布时间】:2014-10-02 13:40:22
【问题描述】:

我一直在为这段代码苦苦挣扎,我是新手,所以请耐心等待。

下面的代码非常适合在一个名为 Blog 的表中进行搜索。不过我还有 3 张桌子,看起来像这样:

--[FE]
----- [Blog]
----- [Bolted_steltanks]
----- [Mixers]
----- [Windpower]

我希望我的代码搜索所有 4 个表,现在它只搜索 1 个表。下面是我的部分代码:

var q = from p in dbBlog.Blog.ToList()

                //join w in dbAlbum.Windpower on p.Description equals w.Description

                where
                    Data.Any(x => p.Description.IndexOf(x) >= 0) ||
                    Data.Any(x => p.Date.IndexOf(x) >= 0)
                orderby p.id descending
                select p;
return View("Found", q.ToList());

另一个小问题是接收结果的视图。我不确定如何创建模型,一张表在这段代码中效果很好:

@model IEnumerable<FE.Blog>

非常感谢任何帮助。

【问题讨论】:

    标签: sql asp.net-mvc linq asp.net-mvc-3


    【解决方案1】:

    您可以像下面这样使用 linq 来连接多个表。

    from t1 in Table1
    join t2 in Table2 on t2.Id equals t1.Id //OR matching field
    join t3 in Table3 on t3.Id equals t1.t3Id //OR matching field
    where t1.ConditionColumn == value // OR all your where clause to come here
    select new { col1 = t1.col1, col2 = t1.col2, col3 = t1.col3, col4 = t2.col1, col5 = t3.col1 }; //OR all your select to come here
    

    我认为不需要@model IEnumerable&lt;FE.Blog&gt;。 / 这样的多表声明

    【讨论】:

    • 如果我在视图中没有任何@model...,我将无法检索任何模型项目,一切都会崩溃。我已经使用了你的代码并且没有出现语法错误,我也没有得到任何结果,也许是因为 View?
    • 我写了一个包含所有需要属性的新模型。 @CodeMad,感谢您的回答,我从这几行中学到了很多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    相关资源
    最近更新 更多