0

我所有的代码都在这里,很简单,我不知道哪里出错了。

Person 和 Task 具有多对多的关系。我想使用显式方式加载某人的任务。我按照这篇文章显示的方式进行操作,但我无法使其工作。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Task> Tasks { get; set; }
}
public class Task
{
    public int Id { get; set; }
    public string Subject { get; set; }
    public ICollection<Person> Persons { get; set; }

}

public class Ctx : DbContext
{
    public Ctx()
        : base("test")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }
    public DbSet<Person> Persons { get; set; }
    public DbSet<Task> Task { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        //add some data as follows
        //using (var ctx = new Ctx())
        //{

            //ctx.Persons.Add(new Person { Name = "haha" });
            //ctx.Persons.Add(new Person { Name = "eeee" });

            //ctx.Task.Add(new Task { Subject = "t1" });
            //ctx.Task.Add(new Task { Subject = "t2" });
            //ctx.SaveChanges();

            //var p11 = ctx.Persons.FirstOrDefault();
            //ctx.Task.Include(p2 => p2.Persons).FirstOrDefault().Persons.Add(p11);
            //ctx.SaveChanges();
        //}

        var context = new Ctx();
        var p = context.Persons.FirstOrDefault();

        context.Entry(p)
        .Collection(p1 => p1.Tasks)
        .Query()
        //.Where(t => t.Subject.StartsWith("t"))
        .Load();

        //the tasks should have been loaded,isn't it?but no...
        Console.WriteLine(p.Tasks != null);//False

        Console.Read();
    }
}

我的代码有什么问题吗?我对 EF 很陌生,所以请有人帮助我。

4

2 回答 2

0

问题是你的.Query()电话。您无需加载集合,而是获取IQueryable将用于加载的副本,然后执行查询。

删除您的.Query()线路,它将起作用。


如果您正在寻找的是收集元素的过滤列表,您可以这样做:

var filteredTasks = context.Entry(p)
                           .Collection(p1 => p1.Tasks)
                           .Query()
                           .Where(t => t.Subject.StartsWith("t"))
                           .ToList();

This will not set p.Tasks, nor is it a good idea to do so, because you'd be corrupting the domain model.

If you really, really want to do that... this might do the trick (untested):

var collectionEntry = context.Entry(p).Collection(p1 => p1.Tasks);
collectionEntry.CurrentValue =
    collectionEntry.Query()
                   .Where(t => t.Subject.StartsWith("t"))
                   .ToList();
于 2012-06-14T15:30:37.983 回答
0

This solution worked for me :

For some reasons EF requires virtual keyword on navigation property, so the entities should be like this :

public class Person
{
    //...
    public virtual ICollection<Task> Tasks { get; set; }
}

public class Task
{
    //...
    public virtual ICollection<Person> Persons { get; set; }

}
于 2013-07-09T07:07:28.330 回答