使用实体框架查询多个条件

时间:2019-11-07 16:48:06

标签: c# entity-framework

如何查询多个条件,并且其中一个条件为空时将被忽略,而其他条件适用?

这是我的代码

            var SalesAsInt = Convert.ToInt32(txtSalesNo.Text);
            var YearAsInt = Convert.ToInt32(cbxYear.Text);
            var MonthAsInt = Convert.ToInt32(cbxMonth.Text);
            var DayaAsInt = Convert.ToInt32(cbxDay.Text);
            using (var dbcontext = new Database.SalesEntities())
            {
                BindingSource VSalesIncome = new BindingSource();
                VSalesIncome.DataSource = dbcontext
                                 .VSalesIncomes
                                 .Where(u => u.SalesCode  == SalesAsInt )
                                 .Where(u => u.YearIncome == YearAsInt)
                                 .Where(u => u.MonthIncome == MonthAsInt)
                                 .Where(u => u.DayIncome == DayaAsInt)
                                 .ToList();

                dgvadministration.DataSource = VSalesIncome;
            }

任何文本框为空时出错

System.FormatException: 'Input string was not in a correct format.'

2 个答案:

答案 0 :(得分:2)

尝试以下两项更改:

int? SalesAsInt = (txtSalesNo.Text == string.Empty) ? null : (int?)Convert.ToInt32(txtSalesNo.Text);

.Where(u => (SalesAsInt == null) ? true : u.SalesCode  == SalesAsInt )

答案 1 :(得分:0)

您可以将Where方法包装在if语句中

var query = VSalesIncome.DataSource = dbcontext.VSalesIncomes
if (SalesAsInt > 0)
    query = query.Where(u => u.SalesCode  == SalesAsInt)
// repeat as needed
VSalesIncome.DataSource = query.ToList()