Phi*_*ace 3 c# entity-framework code-first
首先是一些简要的背景:我使用实体框架V1现有的ASP.NET MVC 1个应用其中工程还算不错,但因为有越来越到40桌的的.edmx越来越笨重,容易出现腐败与Visual Studio 2008设计.我想要做的是看看将DAL迁移到使用EF4和Code-First是否可行.
最初我试图模拟简单的父/子关系,但没有达到很远.我有2个表Client和Address对应于以下POCO类:
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public Address HomeAddress { get; set; }
public Address WorkAddress { get; set; }
// More properties here
}
public class Address
{
public int AddressId { get; set; }
public string NameOrNumber { get; set; }
public string Line1 { get; set; }
// More properties here
}
Run Code Online (Sandbox Code Playgroud)
另外我有一个DbContext类,我使用流畅的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");
}
}
Run Code Online (Sandbox Code Playgroud)
那么在我的控制器中我可以返回以下作为我的模型:
Context.Clients.Take(10).OrderBy(i => i.Name)
Run Code Online (Sandbox Code Playgroud)
从它返回一个默认的从数据库返回10个结果不如预期,除了Address对象Client.WorkAddress和Client.HomeAddress.
我的猜测是,我要么设置ObjectContext.ContextOptions.LazyLoadingEnabled = true在错误的位置,要么(更有可能)我没有得到我的关系Client和Address正确.