Ask Your Question
1

How to indicate the name of the database in EF Core?

asked 2022-05-31 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-11-27 00:00:00 +0000

lakamha gravatar image

In EF Core, you can indicate the name of your database by passing the name to the DbContext constructor or by setting it in the OnConfiguring method of your DbContext class. Here's an example of setting the database name in the constructor:

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // configure your entity mappings here
    }
}

To specify the database name, you can pass it to the base constructor like this:

public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}

// specify the database name in the OnConfiguring method
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDbName;Trusted_Connection=True;");
}

In this example, we've specified "MyDbName" as the name of the database.

Alternatively, you can specify the database name directly in the DbContext constructor like this:

public MyDbContext() : base("name=MyDbName")
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // configure your entity mappings here
}

In this case, we're passing the connection string name "MyDbName" to the base constructor. The actual connection string will be defined in your app.config or web.config file.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-31 11:00:00 +0000

Seen: 12 times

Last updated: Nov 27 '22