Most new projects require some sort of data access method. I used the following steps with an MVC application in Visual Studio 2013, they should be enough to get you started. I am going to assume you have already have an MVC ready project open. To keep the code snippets short not all the namespace references are shown, just the key ones.
Setup the Database
It is up to you what type of database you use, SQLExpress, SQL Server or something else. Create a database and set the permissions as needed, most likely for development you will use integrated security.
For starters add a table to hold product data with the below script.
CREATE TABLE Products ( [ProductID] INT NOT NULL PRIMARY KEY IDENTITY, [ProductCode] NVARCHAR(100) NOT NULL, [Description] NVARCHAR(500) NOT NULL, [UnitPrice] DECIMAL(9, 2) NOT NULL )
For now populate the table with some dummy data.
INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1234', 'Torch', 23.99) INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P3456', 'Toaster', 15.90) INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P7890', 'Football', 10.00) INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1037', 'Hair Net', 3.50) INSERT INTO Product ([ProductCode],[Description],[UnitPrice]) VALUES ('P1634', 'Cooker', 156.99)
Creating a table in the database is actually optional, if you go full Code-First and don’t create a table it will be created automatically by the DBInitializer on the first call requiring the table when the application is run. Just be aware that there will not be any data in the table initially.
Setup EntityFramework
Open the Package Manager Console by going to Tools > Nuget Package Manager > Package Manager Console. At the NuGet command line enter this command to install EntityFramework
Install-Package EntityFramework -projectname DemoApplication
the -projectname switch forces EntityFramework to be installed in a specific project. If you have only one project in your solution you could use
Install-Package EntityFramework
Create a Domain Model
- In your application right-click the Models folder and select Add > Class… (Ctrl+Shift+A).
- In the Add New Item dialog, select Class from the template list and enter a suitable name for your class e.g. Product.cs
- Select the Add button
- Edit the class with the properties you need
namespace DemoApplication.Models { public class Product { public int ProductID { get; set; } public string ProductCode { get; set; } public string Description { get; set; } public decimal UnitPrice { get; set; } } }
Create a DBContext Class
- In your application right-click the Models folder and select Add > Class… (Ctrl+Shift+A).
- In the Add New Item dialog, select Class from the template list and enter a suitable name for your DBContext class e.g. EFDBContext.cs
- Select the Add button
- Edit the class similar to this
using System.Data.Entity; namespace DemoApplication.Models { public class EFDbContext : DbContext { public DbSet<Product> Products { get; set; } } }
The name of the property Products is the name of the table Entityframework will access. The type specified in the DBSet is the object Entityframework will populate.
Add a Connectionstring to Config
The connection string will depend on which database you connected to. AS I was using SQL Server my connectoin string looks similar to this.
<connectionStrings> <add name="EFDbContext" connectionString="Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings>
Create a Repository
- First of all an interface, In your application right-click the Models folder and select Add > New Item… (Ctrl+Shift+A).
- In the Add New Item dialog, select Interface from the template list enter a suitable name for your repository interface e.g. IProductRepository.cs
- Select the Add button
- Edit the repository interface
using SportsStore.Domain.Entities; namespace DemoApplication.Models { public interface IProductRepository { IEnumerable<Product> Products { get; } } }
- Next, the concrete Repository class. In your application right-click the Models folder and select Add > New Item… (Ctrl+Shift+A).
- In the Add New Item dialog, select Class from the template list enter a suitable name for your repository e.g. EFProductRepository.cs
- Select the Add button
- Edit the ProductRepository class as below
using System.Collections.Generic; namespace DemoApplication.Models { public class EFProductRepository : IProductRepository { private EFDbContext context = new EFDbContext(); public IEnumerable<Product> Products { get { return context.Products; } } } }
Controller Setup
In your controller, add a Product Repository
using DemoApplication.Models; namespace DemoApplication.Controllers { public class ProductController : Controller { private IProductRepository repository; public ProductController() { this.repository = new ProductRepository; } public ViewResult Index() { return View(repository.Products); } } }
Controller Setup
The very last thing to do is set up the view to display a list of products.
@model IEnumerable<DemoApplication.Models.Product> @{ ViewBag.Title = "Products"; } <table> @foreach (var product in Model) { <tr> <td>@product.ProductCode</td> <td>@product.Description</td> <td>@product.UnitPrice.ToString("c")</td> </tr> }</table>
This is a bit of a whirlwind tour but hopefullly enough information to get a project going in accessing data with Entityframework.