Database Reference
In-Depth Information
Listing 3-11. Employee Entity Class
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public int? YearsWorked { get; set; }
}
Next, in Listing 3-12, we create the DbContext object required for our Code-First approach.
Listing 3-12. The DbContext Object
public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("ConnectionString") {}
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().ToTable("Chapter3.Employee");
base.OnModelCreating(modelBuilder);
}
}
Since we are implementing the Code-First approach for Entity Framework, we can programmatically assign
default values via a query as shown in Listing 3-13. Note that the pattern in Listing 3-13 doesn't actually materialize
(return from the database) instances of the Employee entity type with the default value. Instead, it projects,
that is, places the results of the query into a collection of an anonymous type whose YearsWorked property is
programmatically set to the value of 0 whenever the underlying value is null. Thus the underlying value in the column
remains NULL, but we project a value of zero as a default value in our Entity Framework result. Keep in mind that an
anonymous type, as shown in Listing 3-13, is a class that gets created on the fly at runtime based on the properties that
we include within the curly braces that immediately precede the new keyword.
Listing 3-13. Using Both LINQ and Entity SQL to Fill in Default Values for Nulls
using (var context = new EFRecipesEntities())
{
// delete previous test data
context.Database.ExecuteSqlCommand("delete from chapter3.employee");
// add new test data
context.Employees.Add(new Employee { Name = "Robin Rosen",
YearsWorked = 3 });
context.Employees.Add(new Employee { Name = "John Hancock" });
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
Console.WriteLine("Employees (using LINQ)");
var employees = from e in context.Employees
select new {Name = e.Name, YearsWorked = e.YearsWorked ?? 0};
Search WWH ::




Custom Search