Shuvro
Shuvro

Reputation: 1499

Joining multiple tables in asp.net mvc5 using Entity Framework

I'm trying to join two models and then select values from the joined table. What I've implemented is by far this from my understanding and gathering informations from different solutions in SO. But in x I'm always getting the values from first context context.EventSessionTeamModels but nothing from the second one. But everything from the Select block is needed to be fetched from the second one context.SessionModels. Maybe I've joined them in a wrong way. I need to know what needs to be done. Let me know if any other portion of the code is need other than the below code.

IQueryable<SessionShortModel>  shortInfoSession = context.EventSessionTeamModels
 .Join(context.SessionModels, x => x.session_id, y => y.session_id, (x, y) => x)
 .Where(x => x.event_id == eid && x.bp_id == attendeeId && x.role_code == "ATD")
 .Select(x => new SessionShortModel {
     StartTime = x.start_date,
     EndTime = x.end_date,
     Day = DbFunctions.TruncateTime(x.start_date),
     Year = x.start_date.Year,
     Month = x.start_date.Month,
     Name = x.session_name
    });

Upvotes: 0

Views: 1344

Answers (2)

Anik Saha
Anik Saha

Reputation: 4494

May be it solve your issue. You get data from first table as you are using "x". Changing variable to "Y" you will get data from second table.

var data =(from ep in context.EventSessionTeamModels
             join e in context.SessionModels on ep.session_id equals e.session_id
             where ep.event_id == eid && ep.bp_id == attendeeId && ep.role_code == "ATD"
             select new SessionShortModel{
                 StartTime = e.start_date,
                 EndTime = e.end_date,
                 Day = DbFunctions.TruncateTime(e.start_date),
                 Year = e.start_date.Year,
                 Month = e.start_date.Month,
                 Name = e.session_name
             });

Upvotes: 1

J4ime
J4ime

Reputation: 155

In EF you must to relationship the entities, EventSessionTeamModels needs has the propierty SessionModels

List<SessionShortModel>  shortInfoSession = context.EventSessionTeamModels
 .Include("SessionModels")
 .Where(x => x.SessionModels.event_id == eid && x.SessionModels.bp_id == attendeeId && x.SessionModels.role_code == "ATD")
 .Select(x => new SessionShortModel {
     StartTime = x.start_date,
     EndTime = x.end_date,
     Day = DbFunctions.TruncateTime(x.start_date),
     Year = x.start_date.Year,
     Month = x.start_date.Month,
     Name = x.session_name
    }).ToList();

Upvotes: 0

Related Questions