实体框架和泛型

时间:2012-10-16 19:58:41

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

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

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的流畅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继承。

我可以看到我在这种情况下尝试使用泛型的明显缺陷。但是,任何人都可以建议我的数据库表结构,类代码或映射代码的替代方案,这将允许我在许多类之间共享单个泛型类型并具有独立的表吗?

1 个答案:

答案 0 :(得分:7)

只需使用普通的继承结构。并且,不使用像EngineeringProjectId这样的特定ID名称,而只使用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的原因。