Динамическая привязка к Sql со списком и столбцом.Содержит
-
20-08-2019 - |
Вопрос
У меня есть текстовое поле, поле со списком, кнопка и DataGridView в форме, которая используется для поиска и возврата информации о клиенте из представления MSSQL (vCustomer).Это отлично работает, но я знаю, что мой код может быть более эффективным.Четыре элемента в выпадающем списке представляют собой столбцы для поиска.
Есть ли простой способ преобразовать следующее в dynamic LINQ в SQL?Я новичок в C #.Я проверил несколько других сообщений, но, похоже, у меня не получается заставить это работать.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// columns to filter for
string[] list = new string[4];
list[0] = "Name";
list[1] = "CustomerAccountNo";
list[2] = "Telephone";
list[3] = "Postal";
// bind to combobox
cboColumn.DataSource = list;
cboColumn.SelectedIndex = 0;
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
Cursor.Current = Cursors.WaitCursor;
CustomerSearchDataContext db = new CustomerSearchDataContext();
IEnumerable<vCustomer> customerQuery = null;
switch (cboColumn.SelectedIndex)
{
case 0:
customerQuery = from c in db.vCustomers
where c.Name.Contains(txtSearch.Text)
orderby c.CustomerAccountNo descending
select c;
break;
case 1:
customerQuery = from c in db.vCustomers
where c.Name.Contains(txtSearch.Text)
orderby c.CustomerAccountNo descending
select c;
break;
case 2:
customerQuery = from c in db.vCustomers
where c.Telephone.Contains(txtSearch.Text)
orderby c.CustomerAccountNo descending
select c;
break;
case 3:
customerQuery = from c in db.vCustomers
where c.Postal.Contains(txtSearch.Text)
orderby c.CustomerAccountNo descending
select c;
break;
}
customerBindingSource.DataSource = customerQuery;
dataGridView1.DataSource = customerBindingSource;
dataGridView1.Columns["CustomerId"].Visible = false;
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show("An Error Occured - " + ex.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
Решение
Использование [System.Linq.Dynamic][1]
.
Получите условие из метода и используйте его в одном запросе.
switch (choice)
{
case case1:
condition = string.Format("{0}.Contains({1})", "Column", "Value"
break;
Другие советы
Привет, Рони.Я попробовал ваше предложение и переработал свой код (см. Ниже).Однако я получаю сообщение об ошибке: В типе 'vCustomer' не существует свойства или поля 'smith' .Кстати, окно сообщения.Показать (условие);возвращает строку Имя.Содержит (smith) что выглядит правильно.
Что я делаю не так?Извините за то, что я нуб, и спасибо за вашу помощь.
Разобрался в этом...необходимо заключить строку поиска в двойные кавычки!Код был отредактирован.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// data column to filter against
string[] list = new string[4];
list[0] = "Name";
list[1] = "CustomerAccountNo";
list[2] = "Telephone";
list[3] = "Postal";
cboColumn.DataSource = list;
cboColumn.SelectedIndex = 0;
// left, right or middle search
string[] list2 = new string[3];
list2[0] = "Contains";
list2[1] = "StartsWith";
list2[2] = "EndsWith";
cboFilterAtt.DataSource = list2;
cboFilterAtt.SelectedIndex = 0;
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
Cursor.Current = Cursors.WaitCursor;
CustomerSearchDataContext db = new CustomerSearchDataContext();
//string condition = string.Format("{0}.{1}({2})", cboColumn.SelectedValue, cboFilterAtt.SelectedValue, txtSearch.Text);
string condition = string.Format("{0}.{1}({2})", cboColumn.SelectedValue, cboFilterAtt.SelectedValue, "\"" + txtSearch.Text + "\"");
MessageBox.Show(condition);
var customerQuery = db.vCustomers.Where(condition).OrderBy("CustomerAccountNo");
customerBindingSource.DataSource = customerQuery;
dataGridView1.DataSource = customerBindingSource;
dataGridView1.Columns["CustomerId"].Visible = false;
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show("An Error Occured - " + ex.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}