无法在Entity Framework中的查询中使用枚举字段

时间:2014-08-23 20:10:29

标签: c# asp.net entity-framework

我正在开发某种CMS,其中我有不同内容类型的层次结构。

基本内容类是:

[Table("Content")]
public abstract class CmsContent {
    public string Content { get; set; }
    public abstract CmsContentType Type { get; }
    public CmsContentLocation Location { get; set; }

    public CmsContent()
    { }
}

CmsContentType是枚举:

public enum CmsContentType: byte {
    None = 0,
    Text = 1,
    News = 2,
    Document = 3,
    Link = 4,
    Image = 5,
    Banner = 6
}

一堆具体内容类型继承自CmsContent,如TextContentImageContent等。

public class TextContent: CmsContent {

    public override CmsContentType Type {
        get { return CmsContentType.Text; }
    }

    public TextContent()
    { }
}

所有这些数据都存储在一个表中。

实体框架上下文(简化):

public class EFDbContext: DbContext {

    public DbSet<CmsContent> Content { get; set; }

    public EFDbContext() { }

    public EFDbContext(string connectionString)
        : base(connectionString) { }

    protected override void OnModelCreating(DbModelBuilder mb) {
        mb.Entity<CmsContent>()
            .Map<TextContent>(m => m.Requires("Type").HasValue(1))
            .Map<NewsContent>(m => m.Requires("Type").HasValue(2))
            .Map<DocumentContent>(m => m.Requires("Type").HasValue(3))
            .Map<LinkContent>(m => m.Requires("Type").HasValue(4))
            .Map<ImageContent>(m => m.Requires("Type").HasValue(5))
            .Map<BannerContent>(m => m.Requires("Type").HasValue(6));
    }
}

问题是当我尝试选择&#39; Type&#39;我收到了错误。

我的查询库:

public class EFCmsContentRepository: EFRepository<CmsContent>, ICmsContentRepository {

    protected override DbSet<CmsContent> Table {
        get { return Context.Content; }
    }

    public CmsContent Find(CmsContentType type) {
        return Table.FirstOrDefault(c => c.Type == type);
    }
}

我收到错误消息:

  

指定的类型成员&#39;类型&#39; LINQ to Entities不支持。仅支持初始化程序,实体成员和实体导航属性。

我使用EF 5支持枚举查询,我有另一个存储库,我通过枚举字段成功选择。

感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

最后,为了解决这个问题,我从每个模型中删除了Type字段。 正如 hvd 所说,我们不应该管理EF背后的属性。此外,不应在模型中定义用于层次结构映射的db表字段(在我的情况下为Type)。 要知道我们可以使用Reflection的内容类型(但它很少需要具有良好的架构)。