一对一到多个EF 6.1.3在第一个'One'关系中加入了很多懒数

时间:2016-05-26 16:13:18

标签: c# sql-server entity-framework entity-framework-6 relational-database

我在没有制作的数据库中有一对一的关系。我已经为EF 6.1.3创建了DbContext和Entities:

public class A{
    public int Id { get; set; }
    public virtual B B { get; set; }
}

public class B{
    public int Id { get; set; }
    public int AId { get; set; }
    public virtual A A { get; set; }
    public virtual ICollection<C> Cs { get; set; }
}

public class C{
    public int Id { get; set; }
    public int BId { get; set; }
    public virtual B B { get; set; }
}

public class MyDb : DbContext {
    public DbSet<A> As { get; set; }
    public DbSet<B> Bs { get; set; }
    public DbSet<C> Cs { get; set; }
}

当我得到A:

var a = MyDb.As.FirstOrDefault();

并且计算相关B的C集合(与A一对一),Cs集合为空:

var countCs = a.B.Cs.Count; // This is 0

当我这样做时:

var b = MyDb.Bs.FirstOrDefault(b => b.AId == a.Id);
var countCs = b.Cs.Count; // This is the correct value

我应该如何建立与数据注释或FluentApi的关系,以使延迟加载从A到Cs工作?

1 个答案:

答案 0 :(得分:1)

请试试这个

public class A
{
    public int AId { get; set; }
    public virtual B B { get; set; }
}

public class B
{
    public int AId { get; set; }
    public virtual A A { get; set; }
    public virtual ICollection<C> Cs { get; set; }
}

public class C
{
    public int Id { get; set; }
    public int BId { get; set; }
    public virtual B B { get; set; }
}
public class MyDb : DbContext
    {
        public DbSet<A> As { get; set; }
        public DbSet<B> Bs { get; set; }
        public DbSet<C> Cs { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<B>()
                .HasKey(p => p.AId);
            modelBuilder.Entity<A>()
                .HasOptional(p => p.B)
                .WithRequired(p => p.A);
            modelBuilder.Entity<C>()
                .HasRequired(p => p.B)
                .WithMany(p => p.Cs)
                .HasForeignKey(p => p.BId);
        }
    }