繁体   English   中英

实体框架的查找方法如何工作?

[英]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
  1. 为什么在Include()调用之后不能在第一种情况下调用Find()方法,但是可以使用Where()和First()?
  2. 如果我对Find()使用第二种情况,那么在这里我无法将Include()方法调用到Lodgings,那么我应该如何加载相关的住宿呢?

我的问题可以用另一种方式表达:

  1. 正确的方法是:找到一个对象并加载所有相关的内部对象(一对多)?
  2. 正确的方法是:加载所有对象(集合A)和内部相关对象(集合AI),然后从(A)中按ID查找一个?

关键是Find从搜索上下文的本地缓存开始。 如果找不到匹配项,则它将查询发送到数据库。

DbSet上的Find方法使用主键值尝试查找上下文跟踪的实体。 如果在上下文中未找到该实体,则将向数据库发送查询以在该数据库中找到该实体。 如果在上下文或数据库中找不到该实体,则返回Null。

我认为这是对IQueryable找不到Find的内在解释。 使用以下代码EF时,始终向数据库发送请求:

var destination = organizationDbContext.Destinations // case # 1
                .Include("Lodgings")
                .First(p=>p.DestinationId==1); 

更多信息: https : //msdn.microsoft.com/zh-cn/data/jj573936.aspx

问题是我们使用了不同的类型,并且其中一种包含查找方法,而另一种则没有:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM