Are generic classes not supported as models in Entity Framework?

asp.net c# database entity-framework orm

Question

I'm attempting to do the following:

public class TrackerContext : DbContext
{
    public bool TrackNewValues { get; set; }

    public TrackerContext(bool trackNewValues = false)
        : base()
    {
        TrackNewValues = trackNewValues;
    }

    public TrackerContext(string connectinString, bool trackNewValues = false)
        : base(connectinString)
    {
        TrackNewValues = trackNewValues;
    }

    public DbSet<AuditLog<string>> AuditLog { get; set; }
    public DbSet<AuditLogChild> LogChildren { get; set; }
}



public class AuditLog<UserIdOrUserNameColumnType>
{
    public AuditLog()
    {
        Children = new List<AuditLogChild>();
    }

    [Key]
    public Guid AuditLogID { get; set; }

    public UserIdOrUserNameColumnType UserId { get; set; }

    [Required]
    public DateTimeOffset EventDateUTC { get; set; }
}

But I supposeDbSet<AuditLog<string>> is not backed. I experience the following error:

Additional information: The type 'TrackerEnabledDbContext.AuditLog`1[System.String]' 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 or generic, and does not inherit from EntityObject.

Are there any techniques I can use?public DbSet<AuditLog<string>> AuditLog { get; set; } ?

1
10
1/4/2015 10:37:55 AM

Accepted Answer

Entity Framework simply does not support generic Entity types, hence you cannot map the generic type. Remember to model your POCO lessons within the restrictions that allow Entity Framework to construct proxies POCO when utilizing the EF Code-First method.

Briefly put, this means that a class of this kind would:

  • Should not have any characteristics
  • ought not to be generic
  • Must be made public
  • unable to be sealed
  • must not be amorphous
  • must have a constructor that is public or protected and has no parameters.
10
5/27/2014 6:58:05 AM

Popular Answer

In Entity Framework, I've had success using generic classes. It will function if you declare your class and DbSet in the manner below.

public class AuditLogString : AuditLog<String>{}

public DbSet<AuditLogString>  AuditLogStrings { get;set;}

[Update] Since I haven't utilized this approach recently and in light of the feedback on this response, I recommend Pawel's response in its place. However, since I was able to use the procedure, I have decided to leave this response in place.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow