C# 无法在实体框架中的查询中使用枚举字段
我正在开发某种CMS,其中我有不同内容类型的层次结构 基本内容类是:C# 无法在实体框架中的查询中使用枚举字段,c#,asp.net,entity-framework,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 CmsCont
[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()
{ }
}
所有这些数据都存储在一个表中
实体框架上下文是(简化的):
公共类EFDbContext:DbContext{
公共数据库集内容{get;set;}
公共EFDbContext(){}
公共EFDbContext(字符串连接字符串)
:base(connectionString){}
模型创建时受保护的覆盖无效(DbModelBuilder mb){
mb.实体()
.Map(m=>m.Requires(“Type”).HasValue(1))
.Map(m=>m.Requires(“Type”).HasValue(2))
.Map(m=>m.Requires(“Type”).HasValue(3))
.Map(m=>m.Requires(“Type”).HasValue(4))
.Map(m=>m.Requires(“Type”).HasValue(5))
.Map(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);
}
}
public类EFCmsContentRepository:EFRepository,ICmsContentRepository{
受保护覆盖数据库集表{
获取{return Context.Content;}
}
公共CMS内容查找(CMS内容类型){
返回表.FirstOrDefault(c=>c.Type==Type);
}
}
我收到的错误消息:
LINQ to实体中不支持指定的类型成员“type”。仅支持初始值设定项、实体成员和实体导航属性
我使用的是EF5,其中支持枚举查询,我还有另一个存储库,在其中我成功地选择了by enum字段
感谢您的帮助。提前感谢。最后,为了解决这个问题,我从每个模型中删除了
Type
字段。
正如hvd所说,我们不应该在EF背后管理房产。此外,不应在模型中定义用于层次映射的db表字段(Type
)。
要知道内容的类型,我们可以使用反射(但是很少需要有好的体系结构)。问题不在于
enum
;如果将其更改为使用int
,也会出现同样的问题。导致异常的原因是缺少属性设置器,以及您试图在EF的背后管理属性。(我将此作为评论而不是答案发布,因为仅仅知道错误并不足以知道如何更改代码,而且我不确定这里最合适的方法是什么。)
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);
}
}