Entity Framework Cache Busting

The DbContext in Entity Framework 6 automatically caches data that it retrieves from your database. This is useful, but sometimes data changes outside your context (perhaps by another user) and you end up with stale data. How can you force Entity Framework to reload the updated data from the database, and when should you do this?

There are several ways to manage this, depending on which version of Entity Framework you are using and what type of application you are writing.

  1. Disable Tracking using AsNoTracking()
  2. Throw away the DbContext and create a new one
  3. Use an ObjectQuery instead of a DBQuery and set MergeOptions
  4. Refresh the Entities
  5. Detatch the Entities
  6. Call GetDatabaseValues to get the updated values for a single Entity
  7. Use the stale data

Code related to this post can be found at https://github.com/codethug/EFCaching

Read More

A Simple interface for fluently mocking a DbSet

You are testing, right? Have you ever used a mock in your test? When testing a class, a mock allows you to create an object that looks just like an object that your class depends on, but acts in a very specific way that you specify for your test, so that you can test your class completely isolated from the rest of your code. If you’re not familiar with mocks, visit Moq’s quickstart guide to get started.

Now that you know about mocks, let’s look at mocking something a little more complicated. If you’ve ever wanted to unit test a method that uses a DbSet<T> to retrieve data, it can be challenging to figure out how to properly mock the DbSet<T>.

Read More

Web API Deep Dive - Testing with EF Rollbacks across HTTP (part 6 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

Overview

A few weeks ago I wrote an article called Cleaning Up EF 6 Tests With Transactions Rollbacks, where I showed how to create integration tests that set up some data in a database, run a test against the data, and then roll back all changes to the data. The rollback was possible because all of the changes to the data were wrapped up inside a transaction.

This posts extends that idea, but instead of a test calling methods on a repository or service layer, this test makes an HTTP call against a Web API endpoint, while preserving the ability to revert all changes to the database as part of a transaction rollback.

The interesting part here is that we will create a database context, start a transaction against that context, create some test data, and then spin up a Web API server that uses that same context. When we’re done with our tests, we’ll roll back the transaction so that the database changes are all reverted.

2016-01-27 Update - clarified when Configuration is available in an API Controller

Read More

Web API Deep Dive - DTO Transformations and Automapper (Part 5 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

Data Transfer Objects

First, off what is this DTO thing? A Data Transfer Object is an object structure that you use to transfer data across the wire. Sometimes it will look exactly like your entity framework entities. Sometimes it will be different.

For example, suppose you have a database with Customers and Invoices, and your tables look like this:

1
2
3
4
5
6
7
8
9
10
11
12
Customer Table
--------------
CustomerId
Name
City
Telephone

Invoice Table
-------------
InvoiceId
CustomerId
Amount

These are also what your Entity models look like, because entity models reflect the database structure.

Now suppose that you want to provide an API endpoint that returns a list of customers in a particular city with the number of invoices for each customer.

Read More

Web API Deep Dive - OData URL Query Options (Part 4 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

OData URL Query Options

In your API, have you ever created a GET /Orders endpoint, then you discover you need to support paging, so you add an GET /Orders?start={start}&pageSize={pageSize} endpoint? Then you learn another endpoint is needed for sorting by Date, so you also create GET /OrdersByDate and GET /OrdersByDate?start={start}&pageSize={pageSize} endpoints. Before you know it, even though it feels like it should only be a single method, you end up with a collection of endpoints that all do pretty much the same thing except for basic sorting and filtering.

There is an easier way.

Turn on OData URL Query options. To do this, open App_Start\WebApiConfig.cs and add this to the top of the Register method:

1
2
3
// Allow OData Queries on all methods that return IQueryable
System.Web.Http.OData.Extensions
.HttpConfigurationExtensions.AddODataQueryFilter(config);

Read More

Web API Deep Dive - HTTP Error Codes from Exceptions (Part 3 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

HTTP Error Codes from Exceptions

In the last post, we looked at how you can specify HTTP Response codes to return from your API controller when everything is working properly. However, sometimes a problem will occur deep inside your code. Continuing down the REST path, when problems occur, you should use the semantics of HTTP by returning an HTTP status code that reflects the error. When problems occur in your code, exceptions are typically thrown. This week we will be looking at how we can specify the HTTP Response code and content to return depending on the exception that is thrown.

Feb 10, 2016 Update - Fixed bug in second code block

This is a matter of style, but the first thing that I like to do is to create a custom exception, so that I know that what I’m doing will only apply when I specifically raise my custom exception.

Read More