DataContext缺少where语句中的属性

时间:2013-08-15 01:25:08

标签: asp.net-mvc entity-framework entity-framework-5

有些人可以告诉我为什么在使用select语句之后我的where语句中没有属性

db.Select(x => x.Lft).Where(x => x.DepartmentId == id); 
// missing properties in the where clause

你能否帮我纠正我的代码来实现它,请给我一个例子来说明如何实现这一点谢谢

类:

public class Department
{
    public Department()
    {
        Products = new List<Product>();
    }

    public long DepartmentId { get; set; }

    [Required(ErrorMessage="Please enter a name for the departments.")]
    [DataType(DataType.Text)]
    public string Name { get; set; }

    [DataType(DataType.Text)]
    [Required(ErrorMessage = "Please enter a valid url for the department.")]
    public string Url { get; set; }

    public int Lft { get; set; }
    public int Rgt { get; set; }
    public bool MenuItem { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

我的DataContext类

internal class DepartmentsTypeConfiguration : EntityTypeConfiguration<Department>
{
    public DepartmentsTypeConfiguration()
    {
        Property(department => department.DepartmentId)
            .HasColumnName("DepartmentId")
            .HasDatabaseGeneratedOption(databaseGeneratedOption: DatabaseGeneratedOption.Identity);

        Property(department => department.Name)
            .HasColumnName("Name")
            .IsRequired();

        HasKey(key => key.DepartmentId)
            .HasMany(x => x.Products)
            .WithRequired(x => x.Department)
            .WillCascadeOnDelete(true);            
    }
}


public class LeapFrogDataContext : DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<ProductSpecification> ProductSpecifications {get; set;}
    public DbSet<Specification> Specifications { get; set; }
    /**/
    static LeapFrogDataContext()
        //: base("name=LeapFrogDataConnection")
    {
        //Database.SetInitializer(new LeapFrogInitializer());
        //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<LeapFrogDataContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new DepartmentsTypeConfiguration());
        modelBuilder.Configurations.Add(new ProductsTypeConfiguration());
        modelBuilder.Configurations.Add(new SpecificationsTypeConfiguration());
        modelBuilder.Configurations.Add(new ProductSpecificationsTypeConfiguration());

        base.OnModelCreating(modelBuilder);
    }
}

1 个答案:

答案 0 :(得分:4)

db.Select(x => x.Lft)会返回int的列表,因此在where子句中您将无法访问任何属性。

我猜您可以切换selectwhere来实现您想要的效果。假设db是实际的context

db.Where(x => x.DepartmentId == id).Select(x => x.Lft)

这有点奇怪。通常它应该看起来像

db.context.Departments.Where(x => x.DepartmentId == id).Select(x => x.Lft)