从 Sql 获取记录仅用于 asp.net MVC 中 EntityFramewotk 的要求条件

Get records from Sql only for require condition in EntityFramewotk in asp.net MVC

我是 Entity Framework 的新手。 现在,我有一个模型 class:

型号:

public class Search_Model
{

    [Required(ErrorMessage="Gender")]
    public string Gender { get; set; }

    public string Age {get; set;}

    public string Religion { get; set; }

    public string Mothertongue { get; set; }

    public IEnumerable<Search_Model> Searcg_Ie { get; set; }
}

在我的视图中,当用户填写表单并且所有填写的值都出现在上面的模型中,然后它将重定向到以下操作:

操作:

public ActionResult PublicSearch(Search_Model mdl)
    {
        Search_Model srch = new Search_Model();
        srch.Searcg_Ie = new List<Search_Model> { mdl};
        var rtc = srch.Searcg_Ie.Select(z=>z).Where(s=>s!=null).ToList();
        return RedirectToAction("Index", "Home");
    }

所以我的问题是,从上面的模型 Age, Religion, Mothertoungue 字段在运行时可能为空。我想要来自数据库 table 的记录仅用于非空值。 假设只有 Gender & Age 有数据。所以在 entity framework 中我们可以这样写:

return(from x in dbcontext.table1
        where x.age=Age,
        where x.gender = Gender
        select new model{
         model properties here..
        }).ToList();

没关系。但是,当我们不知道哪个 属性 将为空时,我将如何在运行时执行此操作,以及如何编写代码以从 SQL 数据库中获取记录?

我不想使用空模型属性查找记录

return
(from x in dbcontext.table1
    where Age == null || x.age==Age
     && Gender == null || x.gender == Gender
    select new model{
     model properties here..
    }).ToList();

您正在检查您的属性是否等于某个值。任何一个都可以匹配,但如果一个不匹配,则该值不应为空。

return (from x in dbcontext.table1
where (x.age == Age || x.gender == Gender) && (x.age != null && x.gender != null)
select new {/* properties */}).ToList();

您可以通过此查询获得预期的结果

var filteredData = dbContext.table1.Where(x =>!string.IsNullOrEmpty(gender) ? x.Gender == gender : true && !string.IsNullOrEmpty(age) ? x.Age == age : true && !string.IsNullOrEmpty        (religion) ? x.Religion == religion : true).ToList();

您可以根据需要链接任意多个 Where 子句,它们将被翻译成 ands。所以你得到对查询的引用,如果满足你的条件就过滤它。比如你的情况是这样的:

var query = dbcontext.table1;

if(age != null)
    query = query.Where(m => m.Age == age);

if(gender != null)
    query = query.Where(m => m.Gender == gender);

return  query.Select(m => new model
            {
                model properties here..
            }).ToList()