(Linq& EF)其中MyType =(int)枚举不起作用

时间:2014-02-12 04:57:37

标签: linq entity-framework

我在Azure中创建了一个数据库,我从头开始创建(不首先在EF中使用代码),并在我的一个表中创建一个列来表示来自我的C#类的Enum。

枚举

 public enum ItemType
{
    Build,
    Stock,
    Shell,
    Parts,
    [Display(Name="All Vehicles")]
    AllTypesOfVehicles
}  

我试图通过在where子句中使用此枚举来选择EF Linq查询中的某些记录。我只是将枚举转换为其基础的int32数据类型,但它不会检索我想要的结果。

 var results = context.Items.Include(P => P.Manufacturer)
                    .Include(P => P.Category).Include(P => P.VehicleMake)
                    .Include(P => P.VehicleModel).Include(P => P.VehicleYear);

//Fetches specific type of item
if (TypeOfPart != StaticData.ItemType.AllTypesOfVehicles)
{
    results.Where(P => P.Type == (int)TypeOfPart); //This does not work
}
else //fetches all vehicle types
{
    results.Where(P => P.Type == 0 | P.Type == 1 | P.Type == 2);
}  

预计在EF?我知道EF从代码优先方法支持Enum,但我不明白为什么这会导致问题。我进入了Azure门户并编写了一个手动查询,看看我是否能得到我想要的结果。

SELECT * FROM Items WHERE Type = 2  

这只得到了枚举类型为“Shell”的结果。即使将数字2硬编码到我的EF查询中的where子句也不能得到我想要的结果。我重新检查了我的代码,以确保我没有覆盖其他任何地方的where子句,一切看起来都很干净。只是为了确保我甚至在where子句之后调用.ToList()但仍然得到了不好的结果。

我不太确定我在这里缺少什么?

============第一次回答后编辑=======================

 var results = context.Items.Include(P => P.Manufacturer)
                    .Include(P => P.Category).Include(P => P.VehicleMake)
                    .Include(P => P.VehicleModel).Include(P => P.VehicleYear);

                //Fetches specific type of item
                if (TypeOfPart != StaticData.ItemType.AllTypesOfVehicles)
                {
                    var part = (int)TypeOfPart;
                    results.Where(P => P.Type == part);
                    List<Item> t = results.ToList();
                }
                else //fetches all vehicle types
                {
                    results.Where(P => P.Type == 0 | P.Type == 1 | P.Type == 2);
                }

Wrong results

1 个答案:

答案 0 :(得分:0)

  1. 您必须将results.Where()分配回results才能使其正常运行并尝试在EF查询上下文中执行转换:
  2. //Fetches specific type of item
    if (TypeOfPart != StaticData.ItemType.AllTypesOfVehicles)
    {
        var part = (int)TypeOfPart;
        results = results.Where(P => P.Type == part ); //This does not work
    }
    else //fetches all vehicle types
    {
        results = results.Where(P => P.Type == 0 | P.Type == 1 | P.Type == 2);
    }  
    

    顺便说一下,当你试图获取所有类型的车辆时,你是否应该跳过P.Type相关的Where?这意味着您不需要else

    //Fetches specific type of item
    if (TypeOfPart != StaticData.ItemType.AllTypesOfVehicles)
    {
        var part = (int)TypeOfPart;
        results.Where(P => P.Type == part ); //This does not work
    }