我真的很喜欢我的功能。我有桌子和我使用EF。 ORM中该表的表示形式为:
public partial class ProductAttributes
{
public long Id { get; set; }
public System.Guid AttrId { get; set; }
public System.Guid ProdId { get; set; }
public string Value { get; set; }
public virtual Attributes Attributes { get; set; }
public virtual Products Products { get; set; }
}
此表包含产品和属性的FK。该表的主要职责是保持指定产品和属性的价值。正如您所见,值表示为字符串。
使用滑块的网站上的用户设置值的范围。现在我应该从DB中获取所有产品,其中值在用户之间选择。另外,选择可以不是范围,只是表示为字符串的单个值。在这里,我卡住了。
此处用于从DB中选择值的功能:
// Dictionaries Guid - attributeID , string[] - values from slider
public IEnumerable<Products> GetFilteredProducts(Dictionary<Guid, string[]> searchParam)
{
List<Products> list = new List<Products>();
try {
entityContext = new SiteDBEntities();
IQueryable<Products> query = entityContext.Products;
foreach (var item in searchParam)
{
//check do we have single value, it's mean that we whould search equals value
if (item.Value.Length == 1)
{
var r = item.Value[0];
query = query.Where(x => x.ProductAttributes
.Any(y => y.AttrId == item.Key && y.Value.Equals(r)));
}
else
{
double a = Double.Parse(item.Value[0]); // min value
double b = Double.Parse(item.Value[1]); // max value
//AND HERE BECOMES BIG PROBLEMS
// this code will throw error becuase ToDouble cannot be converted to T-SQl
// query = query.Where(x => x.ProductAttributes
// .Any(y => y.AttrId == item.Key
// && Convert.ToDouble(y.Value) > a
// && Convert.ToDouble(y.Value) < b));
//this will return error cannot conver string to double
// query = query.Where(x => x.ProductAttributes
// .Any(y => y.AttrId == item.Key
// && (double)y.Value > a
// && (double)y.Value < b));
// this will return error 'cannot apply ">" to IEnumerable<double>'
// query = query.Where(x => x.ProductAttributes.
// Any(y => y.AttrId == item.Key
// && y.Value.Cast<double>() > a
// && y.Value.Cast<double>() < b));
// }
// this monster that I found on stackoverflow will return an error 'a lambda expression with body cannot be converted to expression tree'
// query = query.Where(x => x.ProductAttributes.Any(p =>
// {
// double val = 0;
// if (double.TryParse(p.Value, out val))
// {
// return p.AttrId == item.Key &&
// val >= a &&
// val <= b;
// }
// else
// {
// return false;
// }
// });
}
}
catch(Exception){}
}