【问题标题】:Entity Framework and generics实体框架和泛型
【发布时间】:2012-10-16 19:58:40
【问题描述】:

我有几个独立的对象,每个对象都有一个公共对象列表。例如,

public class Project 
{ 
   public IEnumerable<CommentEntry<Project>> Comments{get;set;}
}
public class Sample
{ 
   public IEnumerable<CommentEntry<Sample>> Comments{get;set;}
}
public class CommentEntry<T> where T: class
{ 
   public int TId {get;set;}
   public int CommentEntryId{get;set;}
   public DateTime TimeStamp{get;set;}
   public string Comment{get;set;}
}

使用 Entity Framework 5 的 fluent api,我想要一个用于项目和请求的 CommentEntry 表。所以,这是我的映射代码:

modelBuilder.Entity<CommentEntry<Project>>()
            .Map(m =>
                {
                    m.ToTable("EngineeringProjectComments");
                });
        modelBuilder.Entity<CommentEntry<Request>>()
            .Map(m =>
            {
                m.ToTable("SampleRequestComments");
            });

当我尝试迁移时,我遇到以下消息:

类型 CommentEntry`1[Project]' 未映射。使用 Ignore 方法或 NotMappedAttribute 数据注释检查该类型是否被显式排除。验证该类型是否被定义为一个类,不是原始的、嵌套的或泛型的,并且不是从 EntityObject 继承的。

我可以看到我尝试在这种情况下使用泛型的明显缺陷。但是,谁能建议我的数据库表结构、类代码或映射代码的替代方案,让我可以在许多类之间共享单一的通用类型并拥有独立的表?

【问题讨论】:

  • 支持我不在 EF 中映射泛型类型。

标签: c# generics entity-framework-5 fluent-interface


【解决方案1】:

只需使用正常的继承结构即可。而且,不要使用特定的 ID 名称,如 EngineeringProjectId,只需使用 Id。

public class Project 
{ 
   public ICollection<ProjectCommentEntry> Comments{get;set;}
}
public class Sample
{ 
   public ICollection<SampleCommentEntry> Comments{get;set;}
}
public class ProjectCommentEntry : CommentEntry {}
public class SampleCommentEntry : CommentEntry {}
public class CommentEntry
{ 
   public int Id {get;set;}
   public int CommentEntryId{get;set;}
   public DateTime TimeStamp{get;set;}
   public string Comment{get;set;}
}

顺便说一句,您不能在 EF 中将 IEnumerable 用于导航属性,您需要一个完整的集合,这就是您应该使用 ICollection 的原因。

【讨论】:

  • 感谢神秘人。我怀疑这将是一个选择。我试图避免使用在我看来是多余的类。但是,您的解决方案仍然不错。
  • 顺便说一句,任何人都可以阐明在这种情况下阻止使用泛型的技术吗?或者是否有可能包含它的 EF 路线图?
猜你喜欢
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多