Using an mdf file database with Entity Framework Core 2 in Visual Studio 2017

Full source code available here.

If you want to play around with Entity Framework it can be a little frustrating to create a complex database with a lot of sample data. Instead, you could download the Northwind database from Microsoft, it has plenty of tables, a bunch of views and handful of stored procs. More than enough to try out many of the features of EF.

Now, all you have to is figure out how to get access to the db from your application, and it’s not as simple as you might hope. So here’s how to do it in Visual Studio 2017.

Step 1

Download the Northwind database - you can get it here https://www.microsoft.com/en-us/download/details.aspx?id=23654 Install it, it will create some files in c:\SQL Server 2000 Sample Databases.

Step 2

Copy Northwind.mdf and Northwind.ldf to your user directory, something like c:\users\bryan. The Northwind files have to be in that directory to work with the connection string below.

Step 3

Now in Visual Studio use the following connection string.

"Data Source=(LocalDB)\\MSSQLLocalDB;DataBase=Northwind;Integrated Security=True;Connect Timeout=30"

My sample application is a .NET Core Web Api. In startup.cs, add the following -

1public void ConfigureServices(IServiceCollection services)
2{
3	services.AddDbContext<NorthwindContext>(options =>
4		options.UseSqlServer("Data Source=(LocalDB)\\\\MSSQLLocalDB;DataBase=Northwind;Integrated Security=True;Connect Timeout=30"));
5	services.AddMvc();}

If you want to place the database files elsewhere in your filesystem, add an absolute filepath to the connection string.

Step 4

Add an Order.cs class, this represents the orders table from the Northwind database. You can of course add more classes to represent other tables in the Northwind database.

1public class Order
2{
3	public int OrderId { get; set; }
4	public string CustomerID { get; set; }
5	public int EmployeeID { get; set; }
6	public DateTime OrderDate { get; set; }
7	// etc.
8}

Step 5

Add a NorthwindContext class that inherits from DbContext and add the Order DbSet.

1public class NorthwindContext : DbContext
2{
3	public NorthwindContext(DbContextOptions options) : base(options) { }
4	public DbSet<Order> Orders { get; set; }
5}

Step 6

In the controller, add the NorthwindContext to the constructor.

1public OrdersController(NorthwindContext northwindContext)
2{
3	_northwindContext = northwindContext;
4}

Step 7

And finally, use the context in the Get method.

1[HttpGet("{orderId}")]
2public async Task<IActionResult> Get(int orderId)
3{
4	var order = await _northwindContext.Orders.Where(o => o.OrderId == orderId).SingleOrDefaultAsync();
5	return Ok(order);
6}
 
Full source code available here.

comments powered by Disqus

Related