微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 实体框架的Find方法如何工作?

我正在学习实体框架,并且面对一些我无法理解的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; }
}

我通过以下方式处理数据:

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

var destination = organizationDbContext.Destinations.Find(1); // case # 2

>为什么我不能在Include()调用后的第一种情况下调用Find()方法,但可以使用Where()和First()?
>如果我在Find()中使用第二种情况,这里我不能调用Include()方法给Lodgings,那么我应该如何加载相关的寄宿?

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

>正确的做法是:找到一个对象并加载所有相关的内部对象(一对多)?
>正确的做法是:加载所有对象(设置A)和内部相关对象(设置A.I),然后从(A)中通过id找到一个

解决方法

重点是Find通过在上下文的本地缓存中搜索开始.如果未找到匹配项,则会向db发送查询.

The Find method on DbSet uses the primary key value to attempt to find
an entity tracked by the context. If the entity is not found in the
context then a query will be sent to the database to find the entity
there. Null is returned if the entity is not found in the context or
in the database.

我认为这是内在的解释,没有Find on IQueryable.
当您使用以下代码时,EF始终向db发送请求:

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

更多信息:https://msdn.microsoft.com/en-us/data/jj573936.aspx

原文地址:https://www.jb51.cc/csharp/91346.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐