user9934620
user9934620

Reputation:

Linq query not converting to string in MVC app

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

Upvotes: 2

Views: 238

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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;

Upvotes: 3

Related Questions