【问题标题】:c# filter database results using EF similar to SQL WHERE Clausec# 使用类似于 SQL WHERE 子句的 EF 过滤数据库结果
【发布时间】:2016-10-25 13:49:39
【问题描述】:

我已经使用 Entity Framework 连接到我的数据库,并且正在构建我的第一个 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 子句,但由于这是使用实体框架构建的来进行连接,我真的不知道从哪里开始。

任何帮助将不胜感激。

【问题讨论】:

  • 您应该从实体框架教程开始,而不是尝试任意代码。 TBL_Wholesale_UWS_BusinessUnits 是您的实体,即查询的结果。它不是连接到数据库并允许您执行查询的 DbContext 对象。
  • var somethingFilter = testing.Table.Where(x=>x.Field == PrimaryID).Tolist();假设测试是你的 DbContext
  • @Seabizkit testing 是实体,而不是 DbContext。这只是一个空类
  • @PanagiotisKanavos 在阅读了 urs...
  • 你真的应该在开始编码之前做一些阅读。请开始学习 mvc 基本模式。然后,您应该了解有关 EF 的更多信息以及如何实现存储库等常见模式,以便您可以从服务层使用它。 testingclass 只是一个类,而不是 dbcontext。不是我不想回答你的问题,而是我看到你确实需要对这些主题进行深入研究......

标签: c# entity-framework


【解决方案1】:

如果您只是想将那个一个特定对象返回到视图。那么您需要在数据库中找到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);
}

我希望这会有所帮助!

【讨论】:

  • 我会考虑重新格式化 var testing... 行,可能会让初学者感到困惑。
猜你喜欢
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
相关资源
最近更新 更多