How To Combine 2 Tables Using Entity Framework 6 And Linq In An Mvc Project?
I want to know how to get data from relationals tables. I want to get the images from the table named 'Noticias1' that is relationated with 'Noticias' (Noticias is an spanish word
Solution 1:
you will need a view model like this:
internalclassNewsImagesViewModel
{
publicstring Title{ get; set; }
public IEnumerable<Image> Images { get; set; }
//... some other properties
}
In the Controller:
IList<NewsImagesViewModel> newsImagesList;
using (DbContext dbContext = new DbContext())
{
newsImagesList = dbContext.News
.Select(n => new NewsImagesViewModel
{
Title = n.Title,
Images = n.Images,
// ... some other properties you may need
}
.ToList();
}
return View(newsImagesList);
In the View
@model IEnumerable<Your.Namespace.NewsImagesViewModel>
@foreach(var item in Model)
{
//....
}
Solution 2:
First, do yourself a favor and use better names for your classes and properties. You can modify them in the edmx designer as you like, an update won't destroy the changes. Change Noticias1
into the Spanish equivalent of NewsImage and rename the navigation properties.
Secondly, use Include
to get the news images:
var noticias = from n in entities.Noticias.Include(n => n.Noticias2) // TODO: rename!!!where n.Activo && n.FeDesde <= DateTime.Now && DateTime.Now <= n.FeHasta
select n;
Then somewhere within the @foreach (IntranetCorporativa.Model.Noticias n in Model)
you're going to need a @foreach (var image in n.Noticias2)
to display the images.
Post a Comment for "How To Combine 2 Tables Using Entity Framework 6 And Linq In An Mvc Project?"