Isk*_*yev 10 c# entity-framework
我正在学习实体框架,并且面对一些我无法理解的Find()方法.
摘自Julia Lerman的书"编程实体框架:代码优先"
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; }
}
Run Code Online (Sandbox Code Playgroud)
我通过以下方式处理数据:
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
var destination = organizationDbContext.Destinations.Find(1); // case # 2
Run Code Online (Sandbox Code Playgroud)
我的问题可以用另一种方式表达:
Que*_*ger 14
关键是Find从搜索上下文的本地缓存开始.如果未找到匹配项,则会向db发送查询.
DbSet上的Find方法使用主键值来尝试查找上下文跟踪的实体.如果在上下文中找不到该实体,则将向数据库发送查询以在那里找到该实体.如果在上下文或数据库中找不到实体,则返回Null.
我认为这是内在的解释,因为FindIQueryable 没有.当您使用以下代码时,EF始终向db发送请求:
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
Run Code Online (Sandbox Code Playgroud)
更多信息:https://msdn.microsoft.com/en-us/data/jj573936.aspx
| 归档时间: |
|
| 查看次数: |
17273 次 |
| 最近记录: |