2

I use generic repository and I want to use dbcontext without declaration of dbset for each single database model. I tried some solutions but every time I've got this error :

Cannot create a DbSet for 'PointsType' because this type is not included in the model for the context.

public new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
{
  return base.Set<TEntity>();
}

BaseEntity used for generic repository.

Is there anyway to solve this problem ?

2
  • That was added to entity folder in which other entities were placed. In fact, in the same assembly of my DbContext. @GertArnold I got the answer . Thank you anyway. Commented Aug 8, 2021 at 6:11
  • 1
    Next time please try to imagine which information is relevant when asking a question. Also, if the answer helped you, please mark it as accepted, so we see that the question has been dealt with. Commented Aug 8, 2021 at 7:43

1 Answer 1

3

You have to register entities in a DbContext. It can infer relations and discover other entities by itself, but it's better to be explicit about it.

You have two options:

1. Adding DbSet<T> properties to DbContext

One way to do this is to add DbSet<TEntity> properties in DbContext class:

class AppDbContext: DbContext {
    public DbSet<Product> Products { get; set; }
    // ...
}

This is easy, but requires modifying DbContext for every new entity.

2. Implementing IEntityTypeConfiguration<T>

Another way is to implement IEntityTypeConfiguration<TEntity> for all entities, and let DbContext discover configurations using modelBuilder.ApplyConfigurationsFromAssembly method.

Note that there are no DbSet<TEntity> properties in the DbContext class!

class AppDbContext: DbContext
{
    // no DbSet properties 🎉

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

class Product
{
    public int Id { get; set; }
    public string Title { get; set; }
}

class ProductEntityConfiguration: IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.HasIndex(e => e.Title).IsUnique();
    }
}

Now you can access a DbSet for an entity using:

var productSet = dbContext.Set<Product>();

References

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.