【发布时间】:2014-08-23 20:10:29
【问题描述】:
我正在开发某种 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,如TextContent、ImageContent等。
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));
}
}
问题是当我尝试按“类型”字段选择时出现错误。
我的带有查询的存储库:
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);
}
}
我收到的错误信息:
LINQ to Entities 不支持指定的类型成员“类型”。仅支持初始化程序、实体成员和实体导航属性。
我正在使用支持枚举查询的 EF 5,并且我有另一个存储库,我成功地通过枚举字段进行选择。
感谢任何帮助。提前致谢。
【问题讨论】:
-
问题不在于
enum;如果您将其更改为使用int,您将遇到同样的问题。缺少属性设置器,以及您试图在 EF 背后管理属性,导致异常。 (我将其作为评论而不是答案发布,因为仅仅知道出了什么问题不足以知道如何更改您的代码,而且我不确定这里最合适的方法是什么。)
标签: c# asp.net entity-framework