我所有的代码都在这里,很简单,我不知道哪里出错了。
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 很陌生,所以请有人帮助我。