Skip to main content
 首页 » 编程设计

c#之从 IQueryableString> 到 String

2024年02月20日13findumars

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

[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(); 

您还有 First 和 Single 以及 SingleOrDefault

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