我是 EF/LINQ 的新手,尽管进行了搜索,但我似乎无法弄清楚这一点。我正在使用现有的数据库。我有父母,他们与孩子是一对多的关系。我想使用数据库来填充父母列表并填充他们的孩子。所以最后我将收集父母的所有数据,每个父母都有一个孩子列表,其中也填充了数据。但我似乎无法让亲子关系发挥作用。我知道该怎么做:
var query = (from p in myDbContext.Parents
select p);
但这并没有给我 Child 数据。我想出了如何做到这一点:
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());
}
}