Friday, 23 August 2013

How to integrate a Linq to Entity query that queries multiple entities in a repository?

How to integrate a Linq to Entity query that queries multiple entities in
a repository?

I'm learning MVC, the repository pattern and EF and I need some advice as
to how best to integrate a method which contains a query that queries
multiple entities into the repository.
At the moment, I have created a repository class which implements an
interface and uses an instance of DbContext to retrieve data from the
database using the Entity Framework, but for one entity.
public interface IUserJourneyRepository
{
//IQueryable<UserJourney> UserJourneys { get; }
IQueryable<User> Users { get; }
IQueryable<Journey> Journeys { get; }
void SaveJourney(Journey journey);
}
public class EfUserJourneyRepository : IUserJourneyRepository
{
private EfDbContext context = new EfDbContext();
public IQueryable<User> Users
{
get { return context.Users; }
}
public IQueryable<Journey> Journeys
{
get { return context.Journeys; }
}
public void SaveJourney(Journey journey)
{
if (journey.JourneyID == 0)
{
context.Journeys.Add(journey);
}
else
{
Journey dbEntry = context.Journeys.Find(journey.JourneyID);
if (dbEntry != null)
{
dbEntry.FromDestination = journey.FromDestination;
dbEntry.ToDestination = journey.ToDestination;
dbEntry.UserType = journey.UserType;
dbEntry.DepartDate = journey.DepartDate;
dbEntry.DepartTime = journey.DepartTime;
dbEntry.ReturnDate = journey.ReturnDate;
dbEntry.ReturnTime = journey.ReturnTime;
dbEntry.JourneyType = journey.JourneyType;
dbEntry.JourneyDescription = journey.JourneyDescription;
}
}
context.SaveChanges();
}
I created a ViewModel and included the Linq to Entities query in it which
I know is incorrect. I would like this method inside the repository. How
can this be achieved?
public static List<SearchViewModel> GetJourneys()
{
EfDbContext dbContext = new EfDbContext();
var todayDate = DateTime.Now;
var viewModel = (from j in dbContext.Journeys
from u in dbContext.Users
where j.DepartDate >= todayDate.Date
orderby j.DepartDate ascending
select new SearchViewModel
{
JourneyDestination = j.FromDestination + " -
" + j.ToDestination,
JourneyDate = j.DepartDate,
SeatsAvailable = j.SeatsAvailable,
UserName = u.FirstName + " " + u.LastName,
ProfileImage = u.ProfileImg,
UserType = j.UserType
}).ToList();
return viewModel;
}

No comments:

Post a Comment