c# - 从 IQueryable<String> 到 String

标签 c# asp.net-mvc linq model

我有一个模型,如下所示:

[Table("WebsiteText")]
public class WebsiteTextModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string WebsiteSection { get; set; }

    [DataType(DataType.MultilineText)]
    public string TextToDisplay { get; set; }
}

我有一个 DataContext 类,如下所示:

public class WebsiteTextContext : DbContext
{
    public WebsiteTextContext()
        : base("DefaultConnection")
    {

    }

    public DbSet<WebsiteTextModel> WebsiteText { get; set; }
}

我想使用 LINQ 获取主页的网站文本,并将其填充到 ViewBag 中,所以我正在尝试这样做:

public ActionResult Index()
{
    var context = new WebsiteTextContext();

    var result = from x in context.WebsiteText
                 where x.WebsiteSection == "Home Page"
                 select x.TextToDisplay;

    ViewBag.Message = result;

    return View();
}

但是 var 是 IQueryable,我不知道如何将它变成字符串。这不起作用:

string result = from x in context.WebsiteText
    where x.WebsiteSection == "Home Page"
    select x.TextToDisplay;

这行不通:

var result = from x in context.WebsiteText
    where x.WebsiteSection == "Home Page"
    select x.TextToDisplay.ToString; //It's still IQueryable<String>

这行不通:

var result = from x in context.WebsiteText
    where x.WebsiteSection == "Home Page"
    select x.TextToDisplay.ToArray; //It's now IQueryable<char[]>

我需要做什么?

最佳答案

string result = (from x in context.WebsiteText
where x.WebsiteSection == "Home Page"
select x.TextToDisplay).FirstOrDefault();

您还有 FirstSingle 以及 SingleOrDefault

全部查看并选择最适合您的版本。

关于c# - 从 IQueryable<String> 到 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13367694/

相关文章:

javascript - 如何将选定的值从多选(Kendo MultiSelect)发送到 viewModel

c# - 模型绑定(bind)新的 Datatables 1.10 参数

c# - LINQ没有给出我期望的输出

c# - C# 中的 strtoul 等效项

c# - 未经授权暴露hangfire

c# - 找出项目在哪个页面上

vb.net - 将 Case 语句与表中的 Int 条目一起使用

javascript - 相当于 C# 中的 Javascript Yield* 委托(delegate)给另一个迭代器?

c# - 如何使 Visual Studio 在 C# 代码中自动包含大括号?

C# 项目与 Oracle.DataAccess.dll (v2) 在 Win 7 与 ORA-12154 错误