从IQueryable <string>转到String </string>

时间:2012-11-13 19:50:09

标签: 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[]>

我需要做什么?

1 个答案:

答案 0 :(得分:4)

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

您还有FirstSingle以及SingleOrDefault

查看所有内容并选择最适合您的版本。