2

This fairly simple LINQ query is being used to pull out a record based on its ID field:

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

Model:

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; }
}

I need to use s (string object) to name a folder. Unfortunately this query is not returning a string and I'm getting an error on the last line of code saying: Illegal characters in path.

Can someone please guide.

Thanks

Gilad Green
  • 36,708
  • 7
  • 61
  • 95

1 Answers1

3

The reason you are getting the error is because ToString on the result of the linq does not return what you are expecting. It calls the ToString of the collection object - which returns the class's name.

Your linq returns a colleciton (even if it has a single item in it). What you want to do is to return that one item using FirstOrDefault (Or SingleOrDefault/First/Single):

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

And in that case you can better write:

string s = db.Categories.FirstOrDefault(i => i.CategoryID == model.SelectedCategory)?.Name;
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • What does that `?` in `string s = db.Categories.FirstOrDefault(i => i.CategoryID == model.SelectedCategory)?.Name;` mean? –  Sep 14 '18 at 06:33
  • @Dad It is the Null propagation operator introduced in C# 6.0. `FirstOrDefault` returns `null` in the case of an empty collection and then if you access the properties you will get an exception. This avoids that. – Gilad Green Sep 14 '18 at 06:34