我有一个产品表。我想从这个表中获得一个特定的列(只有名称和价格列),但是我收到了一个错误。我究竟做错了什么?
总结一下,我想写
SELECT名称,…
你也可以尝试这种方式。 它清晰而优化。
using (EtradeContext context = new EtradeContext()) { var result = context.prdcts .Where(x => x.name == "emre") .Select(s => new { name = s.name , price = s.price }).ToList(); return result; }
使用此代码:
public class ProductDTO { public string Name { get; set; } public string Price{ get; set; } } public List<ProductDTO> GetNameAndPrice() { using (EtradeContext db= new EtradeContext()) { return (from p in db.prdcts where p.name == "emre" select new ProductDTO { Name = p.name,Price = p.price }).ToList(); } }
您无法将结果投影到同一实体。你可以做的是使用匿名类型,类似于 DTO , 视图模型 或类似的东西。但是在您的DBSet中使用选择中的相同类将产生您的错误:
var result = (from x in context.prdcts where x.name == "emre" select new ProductDTO { name = x.name, price = x.price }).ToList();
使用此代码
public List<products> GetNameAndPrice() { using (EtradeContext context = new EtradeContext()) { var result = (from x in context.prdcts where x.name == "emre" select new { name = x.name, price=x.price }).ToList(); return result; } }
删除linq代码中的“products”