Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Inject DbContextOptions vs DbContext in a repository EF Core

I have the StudentDbContext

public class StudentDbContext : DbContext
{
    public StudentDbContext()
    {
    }

    public StudentDbContext(DbContextOptions<StudentDbContext> options)
        : base(options)
    {

    }

    public virtual DbSet<Students> Students{ get; set; }

}

and then I have a repository and I try to understand what is the difference if I inject the StudentDbContext vs inject DbContextOptions

Inject the DbContextOptions

class StudentRepository : IStudentRepository
{
    private readonly DbContextOptions<StudentDbContext> _context;

    public StudentRepository(DbContextOptions<StudentDbContext> context)
    {
        _context = context;
    }
}

Inject StudentDbContext

class StudentRepository : IStudentRepository
{
    private readonly StudentDbContext _context;

    public StudentRepository(StudentDbContext context)
    {
        _context = context;
    }
}

Are there any advantages or disadvantages in each case?

question from:https://stackoverflow.com/questions/66063452/inject-dbcontextoptions-vs-dbcontext-in-a-repository-ef-core

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

1 Answer

0 votes
by (71.8m points)

DbContextOptions class is used to create the options to be used by a DbContext. It configures the database (and other options) to be used for the database context. DbContext class contains DbSet properties for each entity in the model. If you try to use DbContextOptions in a repository you will have no access to any model since it doesn't have them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...