Please navigate to the bottom of the page for Table of Contents

Thursday, March 21, 2013

Entity Framework Interview Question – what are the different ways to configure database name?

Entity Framework allows you to create a model (either using code-first approach or modelling tools) which can target an existing database or create a new one. Generally, you would extend DbContext and the derived class would call one of the base constructors of base class to figure out how to connect to the database. The .Net framework now increasingly favors and supports convention over configuration and this is quite evident in how DbContext discovers the database. We will cover a few of the approaches in how a code-first model discovers the database.

Connection by Convention
Let's examine the following code: 

namespace MvcApplication1.Models
{

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

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

}

In the example shown above, if you have not done any other configuration in your application, then calling the parameterless constructor on DbContext will cause DbContext to run in Code First mode with a database connection created by convention. In this example DbContext uses the namespace qualified name of your derived context class — MvcApplication1.Models.UsersContext — as the database name and creates a connection string for this database using either SQL Express or LocalDb as shown below:









Connection by Convention with database name specified
If you do not like the name given by default, you can also specify what database name to use as an argument to the base class constructor as shown in the code below:

    public class UsersContext : DbContext
    {
        public UsersContext() : base("SuperCoolAppDatabase")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

This results in a database being created (or used if existing) with a more cleaner name as shown:








Connection by Convention withconnection string define in app/web config
If you do not like to code your database name in code, you can more easily specify it in the config file for your application. This is also very useful if you would be using something other than SQL Express or LocalDb as your database; e.g. SQL Server, SQL CE, etc. 

Follow the following convention to add a connect string entry in your web.config or app.config:


  <connectionStrings>
    <add name="MyAppConnStr" 
         providerName="System.Data.SqlServerCe.4.0"
         connectionString="Data Source=Blogging.sdf"/>
  </connectionStrings>

Now that you have defined your named connection string, there are two ways in which this can be discovered by the context:
1. If the name (in this case MyAppConnStr) matches the name of the context (with or without the namespace) it will be used. In our example above, this is not true (unless we named the connect string to be UsersContext).
2. The connection string name can be passed as an argument to the base constructor of your context as shown in the code below:

    public class UsersContext : DbContext
    {
        public UsersContext()
            : base("MyAppConnStr")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

 Since the system is flexible enough to use the name passed into DbContext constructor to determine whether it is a connection string name or database name, a good recommendation is to explicitly pass it as name="your conn string name". That makes the definition and intent clear to all and leaves no room for ambiguity. Also, an exception will be thrown if a connection string with the given name is not found.

    public class UsersContext : DbContext
    {
        public UsersContext()
            : base("name=MyAppConnStr")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

To recap, in this post, we explored different means to allow Entity Framework to discover which database to use using the code-first model.

12 comments:

  1. The war between humans, orcs and elves continues earn to die . Lead your race through a series of epic battles, using your crossbow to fend off foes and sending out units to destroy castleshappy wheels . Researching and upgrading wisely will be crucial to your success! There are 5 ages total and each one will bring you new units to train to fight in the war for you cause.
    earn to die 2
    Whatever you do, don’t neglect your home base because you cannot repair it and once it is destroyed, you lose! Age of War is the first game of the series and really sets the tone for the Age of War games . Also try out the Age of Defense series as it is pretty similar.
    In this game, you start at the cavern men’s age, then evolvetank trouble ! There is a total of 5 ages, each with its units and turrets. Take control of 16 different units and 15 different turrets to defend your base and destroy your enemy.
    The goal of the game also differs depending on the level. In most levels the goal is to reach a finish line or to collect tokens. Many levels feature alternate or nonexistent goals for the player. The game controls are shown just under gold miner. Movement mechanisms primarily include acceleration and tilting controls. cubefield
    It consists of a total of 17 levels and the challenge you face in each level increases as you go up. unfair mario The game basically has a red ball that has to be moved across the various obstacles in its path to the goal. slitherio

    ReplyDelete
  2. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this fiel
    Red Ball | | duck life | Slitherio
    Red Ball 2 | Red Ball 3 | Red Ball 4

    ReplyDelete
  3. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone

    ReplyDelete
  4. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.

    ReplyDelete
  5. I think I could probably eat this for dessert! I have never eaten sweet potatoes like this although I have done a similar thing with carrots and loved it.

    ReplyDelete
  6. Thanks for sharing.I hope it will be helpful for too many people that are searching for this topic.I must appreciate the way you have expressed your feelings through your blog!. Click here to play

    ReplyDelete
  7. Thank you very much for your post, it makes us have more and more discs in our life, So kind for you.I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear.

    ReplyDelete