C# 为什么数据库查询看起来像这样?

C# 为什么数据库查询看起来像这样?,c#,sql,asp.net-mvc,C#,Sql,Asp.net Mvc,我想查询数据库并显示结果。这是我的代码: [HttpGet] public ActionResult Index(string message) { var Result = from Client in db.Clients where Clients.ClientName == message select Clients.ClientName; ViewBag.Message = Result;

我想查询数据库并显示结果。这是我的代码:

[HttpGet]
public ActionResult Index(string message)
{
    var Result = from Client in db.Clients
                   where Clients.ClientName == message
                   select Clients.ClientName;

    ViewBag.Message = Result;

    getCurrentUser();
    return View();
}
其中消息是从输入元素获取的变量。我想使用ViewBag.Message在视图中显示它。我在第页看到:

SELECT [Extent1].[ClientId] AS [ClientId], [Extent1].[ClientName] AS [ClientName] FROM [dbo].[Clients] AS [Extent1] WHERE [Extent1].[ClientName] = @p__linq__0

这是什么意思?

只有在循环查询时才会执行查询。因此,您需要调用Result.ToList来实际获取值

[HttpGet]
    public ActionResult Index(string message)
    {
        var Result = from Client in db.Clients
                       where Clients.ClientName == message
                       select Clients.ClientName;

        ViewBag.Message = Result.ToList();

        getCurrentUser();
        return View();
    }
结果变量包含LINQ查询,而不是字符串。由于您暗示要显示一条消息,因此需要获得第一个结果,而不是查询本身:

ViewBag.Message = Result.FirstOrDefault();
但是,这假设您确实希望ViewBag.Message是ClientName数据库列的值,该列又与Message相同,我怀疑这不是您真正想要的

要回答您原来的问题:


您看到的是在DbQuery上调用ToString的结果,这将为您提供用于获取所需数据的SQL查询。

这将打印System.Collections.Generic.List'[Client]。您将需要该列表的第一个元素,不是列表本身当我使用第一个元素时,我有类似的东西:System.Data.Entity.DynamicProxies.Client_02a0bb155c71d9541e0b7869114c4906eb16ff7d51481c04b3895528738517799。这意味着,我的sql命令不好?谢谢,我现在明白了。你们是对的,当我使用FirstOrDefault时,它再次回答了一些奇怪的问题,但它只在我搜索base中现有的ClientName时才回答。