简体   繁体   中英

Where is the proper place to add a method to handle SQL Connection String in ASP.NET WebAPI

I have a set of many databases that follow the same schema and I've abstracted the pertinent tables in the Model layer of the application. I'm using SQLConnections to handle connecting to the database and Data Adapters and Data Tables to store and move the information back to and through the controllers etc. The code below is what I am currently using, which is working fine for now:

using (SqlConnection con =    
    new SqlConnection(
    "server=MyServersIp\\NameofInstance; " +
    "initial catalog=thisisvariable;" +
    "user id=username;" +
    "password=password123;")) { /* Stuff happening here */ }

What I would like to be using is something more like this here:

using (SqlConnection con =    
    new SqlConnection(getConnectionString("databaseIdentifier")) 
    { 
        /* Stuff  still happening here */ 
    }

So I'm looking for the right place to put my method:

public string getConnectionString(string databaseIdentifier)
{ 
    String theConnectionStringIneed = "appropriateConnectionString"
    return theConnectionStringIneed; 
}

I am very new to MVC and Web API in terms of structure etc, and I want to make sure I'm following best practices.

My question is where in the standard structure should such a method go? I want it to be accessible from wherever in the hopes of keeping the whole Connection String process DRY, but I also need it to be somewhat dynamic (definite output based on database identifier input)

It seems like a simple enough question, but all I can find after some dedicated searching is examples on how to use Entity Framework or folks generating databases from a model, etc, not using Connection strings.

Please advise, and thank you as always SO community.

This is meant to answer your more general question of "My question is where in the standard structure should such a method go? " and just expands on it a little with some architectural thoughts...

Not sure if you're already doing so, though I would put your database tasks - as in all your CRUD and connection stuff - into a project of it's own - Data Access layer in this case.. Keep this project separate from your models. - This kind of directly answers your initial question "where should it go..."

You can then add a reference to your model layer. (assuming you have all your models in a project on their own)

This keeps those 2 separate. Why? Well, one day you might decide to use Entity Framework, or some other means of communicating with your database. If that's the case then you only need to change your data access layer. And you can keep your models looking all shiny and new still.

If you want to really push the boat out then create another project that sits between your web site and the, now new, Data Access layer - call it services. This would be your middleman between your database and your website.

You would call this middleman service from your website controllers. The middleman service then runs off to the data access layer. That layer goes to the database, gets the data, populates the models and gives them back to your middleman. Your middleman now applies any business logic related to your site and also transforms your data models to things like view models (skinny versions of your models just for the website view you're showing) - this has the advantage of not sending big complex objects to your views for rendering. It also keeps business logic (which is more often than not related directly to the project calling the middleman) out of your data access and model layers.

Now things are nicely broken up and you can switch bits and bobs out as your requirements change.

So, in a total laymen term.. The workflow would be something like this:

  • User clicks a link

  • Web site controller gets hit to go fetch data...

  • Controller asks the service middleman for the data, but the controller only wants a little bit of it, so asks for a small version (ViewModel)

  • Service middleman says 'ok, gimme a sec..'

  • Service middleman then runs over to the data access layer and says 'Gimme this data' and asks for a full blown model (a row from the DB)

  • The middleman then gets this back from the data access layer and says 'hmm..the controller said he didn't need half of these properties..' so the middleman creates an instance of a ViewModel (that you defined, like a model).

  • The middleman then populates this instance, the view model, with data from the model the data access layer gave it.

  • The middleman might also do some other stuff, businessy-logic stuff..

  • He then hands it back to the controller and says 'there you go govn'er '

  • The controller then returns it in its action result.

And there is a fun lil way to explain it :D

A little side note

You mentioned that people generally seem to create a database from models - this is called Code First. You can also do Database First - exactly as it sounds..

I would, for this, recommend Entity Framework Powertools . It has an awesome reverse-engineer tool which will build all of your models & relationships from your DB. Freakin awesome!

If you put your connection strings in the web.config you can use ConfigurationManager.ConnectionStrings:

var connectionString = ConfigurationManager
    .ConnectionStrings["ConnectionName"].ConnectionString;

MSDN

I ended up adding a public static method to the WebApiConfig.cs file. This method takes in an identifier and spits back the connection string. There only needs to be the one, so this works alright. I'm moving on from this, but if there are comments for or against this method I'd love to hear it. I'm learning this stuff right now and Web API is a far cry from Web Forms. Thanks to all for your attention!

   public static string getConnectionString()
    {
        return "the connection string";
    }

EDIT: After reviewing comments in other answers, I've also added that I'm going to store the better part of the connection string in the web.config and only use the getConnectionString() method to pull from the ConfigurationManager and tack on the initial catalog, the only changing part of the connection string. Thanks all for your attention.

@Darren: I will also definitely look into N-Tier architecture as it looks like a pretty stable way of handling this, although I think it's outside of the scope of my intents as of right now. Thanks all for some excellent information on all sides.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM