First, a little quick reference: I have an existing ASP.NET MVC 1 application using Entity Framework v1 that works quite well, although due to the fact that up to 40 tables happen, .edmx becomes cumbersome and corrupt with Visual Studio 2008 designer. What I want to do is check if it is possible to migrate DAL to use EF4 and Code-First.
At first, I try to simulate a simple relationship between parents and children, but not very far. I have 2 tables Clientand Addressthat correspond to the following POCO classes:
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public Address HomeAddress { get; set; }
public Address WorkAddress { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string NameOrNumber { get; set; }
public string Line1 { get; set; }
}
In addition, I have a class DbContextin which I define relationships using a fluent api:
public class AppContext : DbContext
{
public SlobContext() : base()
{
this.ObjectContext.ContextOptions.LazyLoadingEnabled = true;
}
public DbSet<Client> Clients
{
get;
set;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>().MapSingleType().ToTable("Address");
modelBuilder.Entity<Client>().HasKey(c => c.ClientID);
modelBuilder.Entity<Client>().HasRequired<Address>(c => c.HomeAddress);
modelBuilder.Entity<Client>().HasRequired<Address>(c => c.WorkAddress);
modelBuilder.Entity<Client>()
.MapSingleType(c => new
{
Name = c.Name,
ClientID = c.ClientID,
HomeAddressID = c.HomeAddress.AddressID,
WorkAddressID = c.WorkAddress.AddressID
})
.ToTable("Client");
}
}
, :
Context.Clients.Take(10).OrderBy(i => i.Name)
10 , , , Address Client.WorkAddress Client.HomeAddress.
, ObjectContext.ContextOptions.LazyLoadingEnabled = true , ( ). Client Address.