J33NO
J33NO

Reputation: 939

How to specify an Entity Framework Connection String in API Project

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!

Upvotes: 1

Views: 768

Answers (3)

Kraego
Kraego

Reputation: 3882

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)
        {
        }
     ....

Upvotes: 1

Matt Ghafouri
Matt Ghafouri

Reputation: 1577

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;");
      }
   }
}

Upvotes: 2

Rahul Pandey
Rahul Pandey

Reputation: 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.

Upvotes: -1

Related Questions