2
我是新來EF/LINQ,儘管搜索我似乎無法弄清楚這一點。我正在使用現有的數據庫。我有父母,他們與兒童有一對多的關係。我想使用數據庫來填充父母的列表,其中填充他們的孩子是和。所以最終我會收集父母的所有數據,每個數據都有一個也包含數據的孩子列表。但我似乎無法得到親子關係的工作。我知道如何做到這一點:實體框架,LINQ和填充父模型及其子代
var query = (from p in myDbContext.Parents
select p);
但這並沒有給我子數據。我想通了,如何做到這一點:
var query = (from p in myDbContext.Parents join c in myDbContext.Children
on p.Id equals c.ParentId into gj
from sub in gj.DefaultIfEmpty()
select p);
但就像一個左外連接,我得到的父記錄重複時,他們有多個孩子。我可以通過循環來構建我想要的數據,但我猜測有一種方法實際上是基於這種關係?我最終還需要處理多對多的問題。我的模型是:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
/* and a bunch of other fields */
public Parent()
{
this.Children = new List<Child>();
}
}
public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
}
我的映射:
public class ParentMap : EntityTypeConfiguration<Parent>
{
public ParentMap()
{
this.HasKey(t => t.Id);
HasMany(t => t.Children)
.WithRequired()
.HasForeignKey(t => t.ParentId);
this.Property(t => t.Name)
.HasMaxLength(50);
this.ToTable("Parents");
this.Property(t => t.Id).HasColumnName("ParentId");
this.Property(t => t.Name).HasColumnName("Name");
/* and a bunch of other properties */
}
}
public class ChildMap : EntityTypeConfiguration<Child>
{
public ChildMap()
{
this.HasKey(t => t.Id);
this.Property(t => t.Name)
.HasMaxLength(50);
this.ToTable("Children");
this.Property(t => t.Id).HasColumnName("ChildId");
this.Property(t => t.ParentId).HasColumnName("ParentId");
this.Property(t => t.Name).HasColumnName("Name");
}
}
我的數據方面:
public class myContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
public myContext() :
base("Name=myContext")
{
Configuration.ProxyCreationEnabled = false;
}
static myContext()
{
Database.SetInitializer<myContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ParentMap());
modelBuilder.Configurations.Add(new ChildMap());
}
}
這兩個工作,謝謝! (特別感謝包括與您的答案一起使用 - 它爲我節省了更多搜索空間。) – MysteriousWhisper
當我開始使用EF時,我遇到了同樣的問題,我花了一段時間才找到命名空間。很高興我能幫上忙 :) –