使用LINQ构建动态查询

时间:2012-12-15 17:18:47

标签: mysql asp.net-mvc linq asp.net-mvc-4

我是rebuilding this website php / mysql进入asp.net。我正在构建页面标题中的主卡搜索表单。有一个文本输入,多个下拉列表(都指向不同的列)和一些条件搜索选项。

对于mysql版本,我能够使用条件来构建包含查询的sting,然后执行它。

 //MySql/PHP example
 $query = "SELECT * FROM cards WHERE ";

    //Encounter_set 
if (isset($_GET['Encounter_Set']){
    $query.= "Encounter_Set=:Encounter_Set AND ";
    $queryArray['Encounter_Set'] = $_GET['Encounter_Set'];
}

 //radio statements
switch ($_GET['radio']) {
    case "All":     $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";break;
    case "Title":   $query.= "(Title LIKE :terms)";break;
    case "Traits":  $query.= "(Traits LIKE :terms)";break;
    case "Text":    $query.= "(Shadow_Text LIKE :terms OR Text LIKE :terms)"; break;
    default:        $query.= "(Title LIKE :terms OR Traits LIKE :terms OR Shadow_Text LIKE :terms OR Text LIKE :terms)";
}

 //Finally
 $result = $db_con->prepare($query);

我将如何在LINQ中执行此操作?

1 个答案:

答案 0 :(得分:2)

using (var context = new MyDbContext())
{
    IQueryable<Card> query = context.Cards;
    if (!string.IsNullOrEmpty(Encounter_Set))
    {
        query = query.Where(c => c.Encounter_Set == Encounter_Set);
    }
    switch (radio)
    {
        default:
        case "All":
            query = query.Where(c => c.Title.Contains(terms)
                || c.Traits.Contains(terms)
                || c.Shadow_Text.Contains(terms)
                || c.Text.Contains(terms));
            break;
        case "Title":
            query = query.Where(c => c.Title.Contains(terms));
            break;
        case "Traits":
            query = query.Where(c => c.Traits.Contains(terms));
            break;
        case "Text":
            query = query.Where(c => c.Shadow_Text.Contains(terms)
                || c.Text.Contains(terms));
            break;
    }
    // ...
    return query.ToList(); // Execute the query
}