【问题标题】:Linq query not converting to string in MVC appLinq 查询未在 MVC 应用程序中转换为字符串
【发布时间】:2019-02-18 22:01:59
【问题描述】:

这个相当简单的LINQ 查询被用于根据其ID 字段提取记录:

string s = (from i in db.Categories
            where i.CategoryID == model.SelectedCategory
            select i.Name).ToString();
if (ModelState.IsValid && model.ImageUpload.ContentLength > 0)
{
    string InitialPath = string.Format("/Images/Products/" + s + "/"); 
    var PathWithFileName = Path.Combine(InitialPath, model.ImageUpload.FileName); 

型号:

public class ItemVM
{
    public int? ID { get; set; }
    [Display(Name ="Category")]
    [Required(ErrorMessage ="Please select a category")]
    public int? SelectedCategory { get; set; }
    [Display(Name = "Brand")]
    [Required(ErrorMessage = "Please select a brand")]
    public int? SelectedBrand { get; set; }
    [Display(Name = "Product name")]
    [Required(ErrorMessage = "Please enter the product name")]
    public string ItemName { get; set; }
    [Display(Name = "Price")]
    [Required(ErrorMessage = "Please enter the price")]
    [Range(1, Int32.MaxValue, ErrorMessage = "Value should be greater than or equal to 1")]
    public decimal? ItemPrice { get; set; }
    [Display(Name = "Image Upload"), Required(ErrorMessage = "Product Image must be added.")]
    [NotMapped]
    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUpload { get; set; }
    public IEnumerable<SelectListItem> CategoryOptions { get; set; }
    public IEnumerable<SelectListItem> BrandOptions { get; set; }
}

我需要使用s(字符串对象)来命名文件夹。不幸的是,这个查询没有返回一个字符串,我在最后一行代码中遇到错误: Illegal characters in path.

谁能指导一下。

谢谢

【问题讨论】:

  • 您是否希望从查询中返回一项?
  • 您是否调试并检查过 's' 包含的值?可能是数据库中有错误的数据?
  • @GiladGreen:是的。查询预计只会返回 1 项。

标签: c# asp.net-mvc linq


【解决方案1】:

您收到错误的原因是因为 linq 结果上的ToString 没有返回您所期望的。它调用集合对象的ToString - 返回类的名称。

您的 linq 返回一个集合(即使其中有一个项目)。您要做的是使用FirstOrDefault(或SingleOrDefault/First/Single)返回该项目:

string s = (from i in db.Categories
            where i.CategoryID == model.SelectedCategory
            select i.Name).FirstOrDefault();

在这种情况下,您可以更好地编写:

string s = db.Categories.FirstOrDefault(i => i.CategoryID == model.SelectedCategory)?.Name;

【讨论】:

  • string s = db.Categories.FirstOrDefault(i =&gt; i.CategoryID == model.SelectedCategory)?.Name; 中的 ? 是什么意思?
  • @Dad 是 C# 6.0 中引入的 Null 传播运算符。 FirstOrDefault 在空集合的情况下返回null,然后如果您访问属性,您将获得异常。这可以避免这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 2021-10-14
相关资源
最近更新 更多