WCF Tutorial, Part 3: Create Data Access Library
Code First Model with ADO.NET Entity Framework is used. In this way the database can be defined during the runtime. This will use our Entity Class RoomReservation which has already defined.
- Add a new Class Library project to the solution and name it RoomReservationData.
-
Add reference to
RoomReservationContracts
andEntityFramework
Assemblies.EntityFramework needed to be installed using Nuget Packager Manager
PM> Install-Package EntityFramework
-
Create a new class called RoomReservationContext
RoomReservationData.cs
using System.Data.Entity; using RoomReservationContracts; namespace RoomReservationData { public class RoomReservationContext : DbContext { public RoomReservationContext() :base("name=RoomReservation") { } public DbSet<RoomReservation> RoomReservations { get; set; } } }
-
RoomReservationContext
class derives from the base classDbContext
to act as a context for the ADO.NET Entity Framework and defines a property namedRoomReservations
to return aDbSet<RoomReservation>
. -
DbContext Class represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit.
DbContext
is conceptually similar toObjectContext
. -
DbSet<TEntity>
Class represents a typed entity set that is used to perform create, read, update, and delete operations.DbSet
is not publicly constructible and can only be created from aDbContext
instance. -
The based constructor is called with passing the name of the SQL connection string. If the database does not exist before starting the application, it is automatically created on first use of the context.
-
Add the following connection string to the App.config
App.config
<connectionStrings> <add name="RoomReservation" connectionString="Server=GAVROCHEPC01;Database=RoomReservation; Trusted_Connection=true; Integrated Security=True; MultipleActiveResultSets=True"/> </connectionStrings>
-
Add a class called RoomReservationData to provide read, write functionality
RoomReservationData.cs
using System; using System.Linq; using RoomReservationContracts; namespace RoomReservationData { public class RoomReservationData { public void ReserveRoom(RoomReservation roomReservation) { using (var data = new RoomReservationContext()) { data.RoomReservations.Add(roomReservation); data.SaveChanges(); } } public RoomReservation[] GetReservations(DateTime fromTime, DateTime toTime) { using (var data = new RoomReservationContext()) { return (from r in data.RoomReservations where r.StartTime > fromTime && r.EndTime < toTime select r).ToArray(); } } } }