I am very very new to entity framework so I might have done terrible mistakes. I have two tables in database and I want to join these tables to show in one view page.My code:
CompanyController
using CompanyData.DAL;
using Microsoft.AspNetCore.Mvc;
using CompanyData.Models;
namespace CompanyData.Controllers
{
public class CompanyController : Controller
{
private readonly CompanyDbContext _context;
private readonly JoinAndViewModel _joinAndViewModel;
public CompanyController(CompanyDbContext context, JoinAndViewModel joinAndViewModel)
{
this._context = context;
this._joinAndViewModel = joinAndViewModel;
}
//private ProjectContext db = new ProjectContext();
public IActionResult YetkiYoksa()
{
IEnumerable<Company> objCompaniesList = _context.Companies;
IEnumerable<Component> objComponentList = _context.Components;
var joinAndViewModel = from c in objCompaniesList join co in objComponentList on c.id equals co.company_id
select new JoinAndViewModel { CustC = (IEnumerable<Company>)c, CustCo = (IEnumerable<Component>)co };
return View(joinAndViewModel);
}
}
}
CompanyDbContext
using CompanyData.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace CompanyData.DAL
{
public class CompanyDbContext : DbContext
{
public CompanyDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Component> Components { get; set; }
}
}
I also prepared Component and Company classes.
and one model to join (?) these tables: JoinAndViewModel
namespace CompanyData.Models
{
public class JoinAndViewModel
{
public IEnumerable<Company> CustC { get; set; }
public IEnumerable<Component> CustCo { get; set; }
}
}
And a view that I don’t know what to use as model to be able to use "foreach":
`
@model IEnumerable<JoinAndViewModel>
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>
Company Name
</th>
<th>
Company Type
</th>
<th>
HQ Region
</th>
</tr>
</thead>
<tbody>
@foreach (var company in Model)
{
<tr>
<td>@company.CustC.company_name</td>
<td>@company.CustC.company_type</td>
<td>@company.CustC.hq_region</td>
}
</tbody>
</table>
Any help is greatly appreciated.
2
Answers
so from my understanding of everything is.Are you doing code first approach or SQL ? are your Models a Many to many relationship? or One company and many components?
If Your doing a code first approach your Moduls would be something like example below.
This way gives asp.net.core gives you a shared table.
Of CompanyComponentTable where The Ids are the shared identifier
This would be a one to many.
The one to many gives you a List of components inside every Company.
Either way gives you a table where you can fetch the other part you need. Depends on what you want with the code.
you have to fix model
and the view, replace IEnumerable with JoinAndViewModel