构建动态linq到SQL查询

时间:2010-11-23 07:18:33

标签: linq-to-sql dynamic

我正在尝试根据用户的输入创建Linq查询。编写sql我可以根据所选的值构建一个sql select字符串但是使用linq到sql我不知道该怎么做。我正在使用linq到sql类。这就是我所拥有的

        // Locals
        TalentDBDataContext talentDB = new TalentDBDataContext()
        int minAge = 0;
        int maxAge = 120;
        bool maleChecked = false;
        bool femaleChecked = false;
        List<string> ethnicities = new List<string>();
        List<string> states = new List<string>();

        var formData = Request.Form;
        foreach (string key in formData.AllKeys)
        {
            string val = formData[key];
            switch(key)
            {
                case "AgeMinTxBx":
                    minAge = Int32.Parse(val);
                    break;
                case "AgeMaxTxBx":
                    maxAge = Int32.Parse(val);
                    break;
                case "GenderMaleCB":
                    maleChecked = true;
                    break;
                case "GenderFemaleCB":
                    femaleChecked = true;
                    break;
                case "EthnicitySelector":
                    ethnicities = val.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries).ToList();
                    break;
                case "StateSelector":
                    states = val.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries).ToList();
                    break;
                default:
                    break;
            }
        }

        var results = 
            from t in talentDB.Talent
            (femaleChecked == true) ? where t.  // I don't thing this will work.. 

我有办法做到这一点吗?希望这是有道理的。我喜欢intellisense linq提供和错误检查。也许还有一种方法可以编写常规的sql select字符串,我可以在这种情况下完成它。感谢

1 个答案:

答案 0 :(得分:0)

您可以使用ExecuteQuery方法直接在该数据库上执行SQL查询。