【问题标题】:eager loading collection relationship in EF code first首先在EF代码中急切加载集合关系
【发布时间】:2012-10-15 12:55:51
【问题描述】:

我在c#中首先使用实体​​框架代码4.3

我有以下课程:

Class A
{
public string Name { get; set; }
public List<B> Bs { get; set; }
}

Class B
{
public string Name { get; set; }
}

从 A 到 B 有一对多的关系。 当我尝试从 A 加载 B 列表时。我只从列表中获取第一个元素。

当我执行以下代码时,我希望 a2 包含两个 b,但实际上它只包含一个。有没有人能帮忙找出问题?

B b = new B() {Name = "b"};
A a = new A() {Name = "a", 
Bs = new List<B>() { new B() {Name = "b1"}, new B() {Name = "b2"} };

using (var context = new MyContext())
{
context.As.Add(a);
context.SaveChanges();
}
using (var context = new MyContext())
{
var a2 = (from a in context.As.Include(a => a.Bs)
        where a.Name == "a"
        select a).Single();
}

谢谢

【问题讨论】:

    标签: c# .net entity-framework ef-code-first code-first


    【解决方案1】:

    您能否发布您的实际代码 - 您发布的代码无法编译,但对您的一些括号和变量命名进行了一些小的更改 - 但我得到的结果与您不同,a2 包含两个 B,因为预期的,所以问题可能出在其他地方。这是整个控制台应用程序:

    public class A
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<B> Bs { get; set; }
    }
    
    public class B
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Model : DbContext
    {
        public DbSet<A> As { get; set; }
        public DbSet<B> Bs { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var b = new B() { Name = "b" };
            var a1 = new A()
                {
                    Name = "a",
                    Bs = new List<B>() { new B() { Name = "b1" }, new B() { Name = "b2" } }
                };
    
            using (var context = new Model())
            {
                context.As.Add(a1);
                context.SaveChanges();
            }
            using (var context = new Model())
            {
                var a2 = (from a in context.As.Include(a => a.Bs)
                          where a.Name == "a"
                          select a).Single();
    
                Console.WriteLine(a2.Bs.Count);
            }
    
            Console.ReadLine();
        }
    
    }
    

    【讨论】:

    • 使用你的代码(工作得很好),我设法理解问题是我的类实现了 Icomparable 很糟糕(比较器有问题)。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多