Given
- A pre-existing database called Inventory
- A table named Product in the database
Objective
Access the Product table using entity frameworkSteps
- Create a console application
- Install EntityFramework package using Nuget
- Add the connection string to App.config
<connectionStrings>
<add name="InventoryDbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Inventory;Integrated Security=True;Pooling=False"
providerName ="System.Data.SqlClient"/>
</connectionStrings>
Code
// Class for accessing the rows in the table
// EF would normally look for "Products" table
// Tell EF to look for "Product" table
[Table("Product")]
public class Product
{
public int Id { get; set; }
public string PartNumber { get; set; }
public string PartName { get; set; }
}
// database context for access
public class InventoryDbContext : DbContext
{
static InventoryDbContext()
{
// Turn off EF's database initialization (our database is pre-existing)
Database.SetInitializer<InventoryDbContext>(null);
}
// Set with access to rows in the Product table
public IDbSet<Product> Products { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var ctx = new InventoryDbContext())
{
var products = ctx.Products.ToList();
products.ForEach(p =>
Console.WriteLine("{0}: {1}, {2}", p.Id, p.PartNumber, p.PartName));
}
Console.ReadKey();
}
}
2: 0002, Binder
3: 0003, Marker
Output
1: 0001, Widget2: 0002, Binder
3: 0003, Marker