[英]How does Find method of Entity Framework work?
我正在学习Entity Framework,并且遇到了我无法理解的Find()方法。
示例摘自Julia Lerman的书“ Programming Entity Framework:Code First”
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte?[] Photo { get; set; }
public ICollection<Lodging> Lodgings { get; set; }
public Destination()
{
Lodgings = new List<Lodging>();
}
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
我通过以下方式处理数据:
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
var destination = organizationDbContext.Destinations.Find(1); // case # 2
我的问题可以用另一种方式表达:
关键是Find
从搜索上下文的本地缓存开始。 如果找不到匹配项,则它将查询发送到数据库。
DbSet上的Find方法使用主键值尝试查找上下文跟踪的实体。 如果在上下文中未找到该实体,则将向数据库发送查询以在该数据库中找到该实体。 如果在上下文或数据库中找不到该实体,则返回Null。
我认为这是对IQueryable找不到Find
的内在解释。 使用以下代码EF时,始终向数据库发送请求:
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
问题是我们使用了不同的类型,并且其中一种包含查找方法,而另一种则没有:
1。
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings") // type here is IQueryable<T> no method Find defined
.First(p=>p.DestinationId==1);
2。
// type here is DbSet<T> with defined method Find
var destination = organizationDbContext.Destinations.Find(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.