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.

18 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
  8. To find a greater exposure for your facebook account, Individuals expend bucks to Buy Facebook Followers to quickly find exposure online. buy followers for facebook

    ReplyDelete
  9. Hello there, I found your web site by way of Google even as looking for a comparable
    subject, your website came up, it seems to
    be good. I’ve bookmarked it in my google bookmarks.
    Hello there, simply changed into aware of your weblog thru Google,
    and found that it’s really informative. I am gonna watch out for brussels.
    I’ll be grateful in the event you continue this in future.
    Many people shall be benefited from your writing. Cheers!

    I love this site – its so usefull and helpfull Pakar Seo this website is extremely helpful Pakar Seo its so usefull and helpfull Pakar Seo

    ReplyDelete
  10. Thanks for sharing information to our knowledge, its really useful for me, keep sharing…
    No.1 Electrical Project Center in Chennai | Electrical Project Center in Velachery

    ReplyDelete
  11. Hi Buddy,


    10/10 !!! Thank you for making your blogs an embodiment of perfection and simplicity. You make everything so easy to follow.


    Your program should be able to read from a file the above data into an array and sort the array by the student’s name in an ascending order. Selection sort algorithm is strongly recommended on the array of objects. And also the record office would like to have a sorted class list for each class, freshman, sophomore, junior, and senior.


    I look forward to see your next updates.


    Many Thanks,
    Morgan

    ReplyDelete
  12. Compre documentos en línea, documentos originales y registrados.
    Acerca de Permisodeespana, algunos dicen que somos los solucionadores de problemas, mientras que otros se refieren a nosotros como vendedores de soluciones. Contamos con cientos de clientes satisfechos a nivel mundial. Hacemos documentos falsos autorizados y aprobados como Permiso de Residencia Español, DNI, Pasaporte Español y Licencia de Conducir Española. Somos los fabricantes y proveedores de primer nivel de estos documentos, reconocidos a nivel mundial.

    Comprar permiso de residencia,
    permiso de residenciareal y falso en línea,
    Compre licencia de conducir en línea,
    Compre una licencia de conducir española falsa en línea,
    Comprar tarjeta de identificación,
    Licencia de conducir real y falsa,
    Compre pasaporte real en línea,

    Visit Here fpr more information. :- https://permisodeespana.com/licencia-de-conducir-espanola/
    Address: 56 Guild Street, London, EC4A 3WU (UK)
    Email: contact@permisodeespana.com
    WhatsApp: +443455280186

    ReplyDelete
  13. You shared a very informative article with us. This is very valuable article. You are doing great work. Now its time to avail Kabou taxi cab services in Southfield Mi for more information.

    ReplyDelete