I am learning Entity Framework and faced some moment with Find() method I can't understand.
Sample taken from book of 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; }
}
And I operate with the data in the following ways :
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
var destination = organizationDbContext.Destinations.Find(1); // case # 2
My questions could be expressed in another way:
The point is that Find
starts by searching in the local cache of the context. If no match are found then it sends a query to the 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.
I think it's the inner explanation that there is no Find
on IQueryable. When you are using the following code EF send always a request to the db:
var destination = organizationDbContext.Destinations // case # 1
.Include("Lodgings")
.First(p=>p.DestinationId==1);
More infos : https://msdn.microsoft.com/en-us/data/jj573936.aspx
The problem is that we use different types and one of this types contains method Find while another one doesn't :
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.