Entity Framework for Beginners Part 4 – Extras

This post is part 4 of 4 covering Entity Framework Code-First for Beginners.

  1. Part 1 – Setting Up Entity Framework Code-First for Beginners
  2. Part 2 – Migrations in Entity Framework Code-First
  3. Part 3 – DbContext
  4. Part 4 – Entity Framework Code-First Extras

To this point, we have covered the basics of Entity Framework. In this post, I will go over six things that are not so obvious. Of course, this list is not exhaustive or even extensive but it does cover several that I hope will be useful.

 

 

  1. You can pass the name of a connection string from your configuration file to a DbContext
    ApplicationDbContext context = new ApplicationDbContext("DefaultConnection");

    This requires that you set up a constructor in your DbContext to accept a parameter and then pass that to the base DbContext.

    public ApplicationDbContext(string connectionName) : base(connectionName)
    {
    
    }
  2. You can pass a connection string to a DbContext.
    public ApplicationDbContext(string connectionString)
    {
        Database.Connection.ConnectionString = connectionString;
    }
  3. Entity Framework is open source. You can view it in it’s entirety here.
  4. You can use .AsNoTracking() to increase performance IF you do not need change tracking (you are 100% sure you will not be making changes to the objects that need to be persisted back to the database).
    IQueryable<ApplicationUser> users = Users.AsNoTracking();
  5. You can disable change tracking if you need to write many changes back to the database. You need to understand the risks. Even if you turn change tracking back on, entities that were changed may still be in Entity Framework’s object cache and will not reflect their changed state.
    ApplicationDbContext context = new ApplicationDbContext();
    context.Configuration.AutoDetectChangesEnabled = false;
    //Update thousands of records
    context.Configuration.AutoDetectChangesEnabled = true;
  6. You can execute your own queries against Entity Framework quite easily and even use them to populate entities.
    ApplicationDbContext context = new ApplicationDbContext();
    string id = "66e80932-94a9-4a46-aab5-8be2dc456f49";
    string sql = "SELECT * FROM AspNetUsers WHERE ID = @p0";
    
    ApplicationUser user = context.Set<ApplicationUser>().SqlQuery(sql, id).SingleOrDefault();

 

This wraps up the Entity Framework for Beginners series. I hope you have enjoyed it and have learned a few things a long the way.

Leave a Reply

Your email address will not be published.