Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c# - Are generic classes not supported as models in Entity Framework?

I am trying to do something like this :

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 guess DbSet<AuditLog<string>> is not supported. I get this 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.

Is there any ways I can implement public DbSet<AuditLog<string>> AuditLog { get; set; } ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot map the generic type because Entity Framework simply doesn't support generic Entity types. When using the EF Code-First approach you need to remember that you should model your POCO classes within the constraints that allow Entity Framework to create POCO proxies.

This means, shortly speaking that such a class:

  • Should not contain any attributes
  • Should not be generic
  • Should be public
  • Must not be sealed
  • Must not be abstract
  • Must have a public or protected constructor that does not have parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...