Pankaj kumar jha
Pankaj kumar jha

Reputation: 133

How to fetch multiple record through entityframework

I have three tables

  1. Employee (ID numeric, Name varchar)
  2. Login (ID numeric, UserName varchar, Password varchar)
  3. EmployeeLogin (ID numeric, EmployeeID, LoginID)

Relation is one employee can have multiple login. How will I get all the Login Name of a particular Employee.

I am able to fetch single record using the code given below but how will I get multiple records

using (var context = new AllEntities())
{
      var query = from c in context.Employees
                     where c.ID == 9
                     select c;
}

Upvotes: 1

Views: 3585

Answers (2)

tdykstra
tdykstra

Reputation: 6050

You should have all of the Logins in a navigation property on the Employee entity. See this tutorial:

http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-1

You can let the Entity Framework get the related data automatically or you can do it manually; for descriptions of lazy vs. eager loading see these tutorials:

http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-2

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

Upvotes: 1

granaker
granaker

Reputation: 1328

The EmployeeLogin table seems redundant if you only have a one-to-many relationship between Employee and Login. You could just place a column EmployeeId in the Login table. The setup you have right now supports many-to-many between Employee and Login.

If you change your model according to my suggestion you could then get all Logins for a EmployeeId like this:

            var query = from c in context.Logins
                        where c.EmployeeID == 9
                        select c;

If you keep your current model you could get all logins for an employee id like this:

            var query = from l in context.Logins
                        join el in context.EmployeeLogins
                        on l.LoginId equals el.LoginId
                        where el.EmployeeID == 9
                        select l;

Upvotes: 4

Related Questions