9

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

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

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

4

1 回答 1

7

只需使用正常的继承结构。并且,不要使用特定的 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;}
}

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

于 2012-10-16T20:30:52.353 回答