这个相当简单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.有人可以请指导。
1 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
您收到错误的原因是因为ToStringlinq 的结果没有返回您所期望的。它调用ToString集合对象的 - 返回类的名称。
您的 linq 返回一个 colleciton (即使它有一个项目)。您要做的是使用FirstOrDefault(或// SingleOrDefault)返回该项目:FirstSingle
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;
有关不同方法的更多信息:Entity Framework 4 Single() vs First() vs FirstOrDefault()(EF 的部分在这里不相关)。
对于 Null 传播,请阅读此处:C#:新的和改进的 C# 6.0
- 1 回答
- 0 关注
- 130 浏览
添加回答
举报
0/150
提交
取消