1

我正在构建一个查询以返回与过滤器值匹配的组件,但是当我尝试添加一个新过滤器时遇到了

从范围“”引用的“组件”类型的变量“c”,但未定义

我一直在缓慢地建立查询,并按照我的意愿进行以下工作

public ActionResult Index(string searchString, string typeFilter)
{

  Supplier supplierAlias = null;
  var query = Session.QueryOver<Component>()
                   .JoinAlias(x => x.Supplier, ()=> supplierAlias);

  if (!string.IsNullOrWhiteSpace(searchString))
      query = query.WhereRestrictionOn(c => c.Name)
                 .IsInsensitiveLike(String.Format("%{0}%", searchString));

  switch (sortOrder)
  {
      case "Component desc":
          query = query.OrderBy(c => c.Name).Desc;
          break;
      case "Type":
          query = query.OrderBy(c=>c.ComponentType).Asc;
          break;
      case "Type desc":
          query = query.OrderBy(c=>c.ComponentType).Desc;
          break;
      default:
          query = query.OrderBy(c => c.Name).Asc;
          break;
  }

  var result = query.List();
  return View(result);
}

但是现在我想在其中添加用户选择Type要过滤的选项,其方式与searchString当前有条件地用于添加 Where 的方式相同。如果typeFilter给出了,那么在哪里添加另一个,但是当我尝试时,我会抛出异常。

I have tried with a Where, WhereRestrictionOn and And - I've also tried moving the typeFilter block above the searchString block but they all give the same result - which is the exception.

if (!string.IsNullOrWhiteSpace(typeFilter))
    query = query.And(c=>c.ComponentType.ToString() == typeFilter);

the ComponentType is an enum that I want to allow the user to filter on.

Edit (the answer)
OK the answer was to use Enum.Parse as Rob G said; it is a bit 'fiddly' so I'm posting the code that works here because it's easier to read here than in a comment.

query = query.Where(c=> c.ComponentType == (Component.ComponentCode)Enum.Parse(typeof(Component.ComponentCode), typeFilter));
4

1 回答 1

2

Use Enum.TryParse

TheEnum enumType;
if (!string.IsNullOrWhiteSpace(typeFilter))
     query = query.And(c => Enum.TryParse<TheEnum>(typeFilter, out enumType) && enumType== c.ComponentType)
于 2013-03-30T16:36:55.377 回答