1

Question: How do I specify the Entity Framework connection string within a .NET API?

I am accustomed to creating a DAL class and specifying the base connection string like I did here.

    public class LocalContext : DbContext
    {
        public LocalContext() : base("LocalDBContext")
        {
        }

        public DbSet<Weapons> Weapons { get; set; 
    }

Which in turn grabs the LocalDBContext connection string from the web.config or appsettings.json.

  "ConnectionStrings": {
    "LocalDBContext": "Server=.;Database=Weapons;Trusted_Connection=True;"
  },

This is what I have done in the past in various web apps but not sure if I have to do something different with an API?

I would expect it to call and save into "Weapons" at "Server=." however it instead created a new Database called "LocalDBContext" at the connection of "(localdb)\mssqllocaldb". Any tips would be greatly appreciated!

3 Answers 3

2

In EF core you don't need to send a connection to the base class with the constructor, just follow this approach:

public partial class LocalContext : DbContext
{
 public LocalContext ()
 {
 }

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

public virtual DbSet<Weapon> Weapons { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        //warning You can move this code to protect potentially sensitive 
          information
        //in connection string.

        optionsBuilder.UseSqlServer("Data Source= .;Initial
                       Catalog=Weapons;Trusted_Connection=True;");
      }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The given String "LocalDBContext" is interpreted as Connectionstring, see official Documentation on DbContext(String).

Do something like:

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

Comments

-1

I have some questions below:

Questions:

  1. Did you add Entity data model in your API solution?
  2. If yes, didn't you save connection string in config file while adding EDM?

While adding EDMX in solution, model window asks to connect the database. Once EDM connects with database, it asks to save connection string in configuration file. You can add tables, functions, SPs, views. This way EDM connects with actual database rather picking different database.

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.