c#使用EF过滤数据库结果,类似于SQL的WHERE子句

本文关键字:SQL 类似于 WHERE 子句 结果 使用 EF 过滤 数据库 | 更新日期: 2023-09-27 18:14:54

我已经使用实体框架连接到我的数据库,并正在构建我的第一个MVC应用程序用于网页。

我可以让控制器在我的模型中填充公共字符串没有问题…我遇到的问题是,我不知道如何从我的数据库过滤响应。

我希望只返回一个项目,我将在视图中显示@Model.BusinessUnit

这是我的模型类的数据库表:

public partial class TBL_Wholesale_UWS_BusinessUnits
{
    public int PrimaryID { get; set; }
    public string BusinessUnit { get; set; }
    public string Status { get; set; }
}

这是我在控制器中的内容:

public ActionResult test(int PrimaryID)
{
    var testing = new TBL_Wholesale_UWS_BusinessUnits();
    // maybe putting new is the wrong thing to do as that would be wiping the class? IDK
    return View(testing);
}

正如您所看到的,PrimaryID通过查询字符串传递给控制器,这是没有问题的识别,但我不知道在哪里添加过滤器,我假设它会像…

var testing = TBL_Wholesale_UWS_BusinessUnits.Where(TBL_Wholesale_UWS_BusinessUnits.PrimaryID = PrimaryID);` 

但是Visual Studio明确地告诉我这是错误的。

如果这是经典的asp,我就会做一个记录集,并使用SQL中的where子句,但由于这是与实体框架一起构建的,我不知道从哪里开始。

c#使用EF过滤数据库结果,类似于SQL的WHERE子句

如果您只是试图将一个特定对象返回给视图..然后您需要在数据库中找到int PrimaryID并检索该特定记录。

你所做的只是创建一个TBL_Wholesale_UWS_BusinessUnits类的新实例,它是

试试这个:

public ActionResult test(int PrimaryID)
{
    var testing = db.TableName.Find(PrimaryID);
    // db = Whatever the variable holding your connection string is.. maybe DbContext
    // TableName = Whatever table in your database that holds the record you want
    // This will return the specific object that you are looking for
    return View(testing);
}

我希望这对你有帮助!