is it ok to call the same Linq query multiple times for loading object from DB in same action method

Joined
Oct 31, 2021
Messages
13
Programming Experience
Beginner
Below is My Controller action in the first line I have gotten the student from db and in 5 line I have use service function in which I have passed the student id which will again load the student from db is it good


Controller Action:
 public ActionResult DeleteStudentInterest(int studentId, String interestName, string navigateUrl)
        {
            var student = _studentService.Get(studentId);
          // Do some Work 
            if (savedStudentInterest != null)
            {   
          [B]      _applicationService.DeleteStudentInterest(savedStudentInterest, id);
 [/B]           }
            return Redirect(navigateUrl);
        }


Service Function:
 public void DeleteStudentInterest(string studentInterest, Student student)
        {
         var student = _db.student.firstordefault(s=>s.Id==id);
       // Do Some Work
            _db.SaveChanges();
        }
 
No it is not. If you have the object available just simply pass the object as the parameter instead of the id.
Check this video on Primitive Obsession for better understanding the concept
 
As a minor aside, it looks like you are actually talking to Entity Framework in your code there, rather than a true LINQ to SQL. Be aware that EF does object caching. So in this case it wouldn't matter if you you tried to query for the same student id. EF will give you back the same object that it already has in memory without incurring a database query hit.

In general, though, as noted above, you should really pass the object that you already have instead of doing another query. Sometimes though you can take advantage of the behavior of your ORM, if you are using an ORM. to your benefit.
 

Latest posts

Back
Top Bottom