【发布时间】:2010-08-03 16:10:09
【问题描述】:
我猜这是不可能的,但无论如何我都会把它扔掉。在 CTP4 中使用 EF4 CodeFirst API 编程时是否可以使用 CreateSourceQuery?我想急切地加载附加到属性集合的属性,如下所示:
var sourceQuery = this.CurrentInvoice.PropertyInvoices.CreateSourceQuery();
sourceQuery.Include("Property").ToList();
当然 CreateSourceQuery 是在 EntityCollection<T> 上定义的,而 CodeFirst 使用普通的旧 ICollection(显然)。有什么方法可以转换吗?
我已经完成了以下工作,但这并不是我想要的。有谁知道如何从下面到上面(下面的代码来自一个继承 DbContext 的类)?
ObjectSet<Person> OSPeople = base.ObjectContext.CreateObjectSet<Person>();
OSPeople.Include(Pinner => Pinner.Books).ToList();
谢谢!
编辑:这是 zeeshanhirani 发布的我的解决方案版本 - 顺便说一句,谁的书太棒了!
dynamic result;
if (invoice.PropertyInvoices is EntityCollection<PropertyInvoice>)
result = (invoices.PropertyInvoices as EntityCollection<PropertyInvoice>).CreateSourceQuery().Yadda.Yadda.Yadda
else
//must be a unit test!
result = invoices.PropertyInvoices;
return result.ToList();
EDIT2:
好的,我刚刚意识到您不能在使用动态时分派扩展方法。所以我想我们不像 Ruby 那样动态相当,但是上面的例子很容易修改以符合这个限制
EDIT3:
正如 zeeshanhirani 的博客文章中提到的,这仅在(且仅当)您具有启用更改的代理时才有效,如果您的所有属性都被声明为虚拟,则会创建该代理。这是将 CreateSourceQuery 与 POCO 结合使用的方法的另一个版本
public class Person {
public virtual int ID { get; set; }
public virtual string FName { get; set; }
public virtual string LName { get; set; }
public virtual double Weight { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Book {
public virtual int ID { get; set; }
public virtual string Title { get; set; }
public virtual int Pages { get; set; }
public virtual int OwnerID { get; set; }
public virtual ICollection<Genre> Genres { get; set; }
public virtual Person Owner { get; set; }
}
public class Genre {
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual Genre ParentGenre { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class BookContext : DbContext {
public void PrimeBooksCollectionToIncludeGenres(Person P) {
if (P.Books is EntityCollection<Book>)
(P.Books as EntityCollection<Book>).CreateSourceQuery().Include(b => b.Genres).ToList();
}
【问题讨论】:
-
查看实际类型(实现
ICollection)。你可以投吗? -
是的,克雷格,你一直都做对了。