質問

This is my first post :) I'm new to MVC .NET. And have some questions in regards to Entity Framework functionality and performance. Questions inline...

class StudentContext : DbContext
{
    public StudentContext() : base("myconnectionstring") {};
    public DbSet<Student> Students {get; set; }
    ...
}

Question: Does DbSet read all the records from the database Student table, and store it in collection Students (i.e. in memory)? Or does it simply hold a connection to this table, and (record) fetches are done at the time SQL is executed against the database?

For the following:

private StudentContext db = new StudentContext();
Student astudent = db.Students.Find(id);

or

var astudent = from s in db.Students
               where s.StudentID == id)
               select s;

Question: Which of these are better for performance? I'm not sure how the Find method works under-the-hood for a collection?

Question: When are database connections closed? During the Dispose() method call? If so, should I call the Dispose() method for a class that has the database context instance? I've read here to use Using blocks.

I'm guessing for a Controller class get's instantiated, does work including database access, calls it's associated View, and then (the Controller) gets out of scope and is unloaded from memory. Or the garbase collector. But best call Dispose() to do cleanup explicitly.

役に立ちましたか?

解決

The Find method looks in the DbContext for an entity which has the specified key(s). If there is no matching entity already loaded, the DbContext will makes a SELECT TOP 1 query to get the entity.

Running db.Students.Where(s => s.StudentID == id) will get you a sequence containing all the entities returned from a SQL query similar to SELECT * FROM Students WHERE StudentID = @id. That should be pretty fast; you can speed it up by using db.Students.FirstOrDefault(s => s.StudentID == id), which adds a TOP 1 to the SQL query.

Using Find is more efficient if you're loading the same entity more than once from the same DbContext. Other than that Find and FirstOrDefault are pretty much equivalent.

In neither case does the context load the entire table, nor does it hold open a connection. I believe the DbContext holds a connection until the DbContext is disposed, but it opens and closes the connection on demand when it needs to resolve a query.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top