Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and generics

I have a couple independent objects, each of which has a list of a common object. For instance,

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;}
}

Using fluent api of Entity Framework 5, I would like a CommentEntry table for Projects and Requests. So, here is my mapping code:

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

When I attempt my migration I encounter the following message:

The type CommentEntry`1[Project]' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

I can see the obvious flaw of my attempt to use generics in this context. However, can anyone suggest an alternative to my database table structure, classes code or mapping code that will allow me to share the single, generic type among many classes and have independent tables?

like image 926
KillerCoder Avatar asked Oct 16 '12 19:10

KillerCoder


1 Answers

Just use the normal inheritance structure. And, instead of using a specific ID name, like EngineeringProjectId, just use 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;}
}

By the way, you can't use IEnumerable for navigation properties in EF, you need a full collection which is why you should use ICollection instead.

like image 160
Erik Funkenbusch Avatar answered Nov 12 '22 10:11

Erik Funkenbusch