I have two tables with the id columns joined in a third table. In my controller, I am returning a single item from 1 table and need to list items from a second table that relates to the single item from the first table. Here is my current broken code:
Depots Model:
public class Depot
{
public int DepotID { get; set; }
public string Name { get; set; }
public virtual ICollection<VendorDepot> VendorDepots { get; set; }
}
Vendors Model:
public class Vendor
{
public int VendorID { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<VendorDepot> VendorDepots { get; set; }
}
VendorDepots Model(join table):
public class VendorDepot
{
public int VendorDepotID { get; set; }
public int DepotID { get; set; }
public int VendorID { get; set; }
public virtual Depot Depot { get; set; }
public virtual Vendor Vendor { get; set; }
}
Context file:
public class GuideContext : DbContext
{
public GuideContext(DbContextOptions<GuideContext> options)
: base(options)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VendorDepot>()
.HasKey(t => new { t.VendorID, t.DepotID });
modelBuilder.Entity<VendorDepot>()
.HasOne(pt => pt.Vendor)
.WithMany(p => p.VendorDepots)
.HasForeignKey(pt => pt.VendorID);
modelBuilder.Entity<VendorDepot>()
.HasOne(pt => pt.Depot)
.WithMany(t => t.VendorDepots)
.HasForeignKey(pt => pt.DepotID);
}
public virtual DbSet<Depot> Depots { get; set; }
public virtual DbSet<VendorDepot> VendorDepots { get; set; }
public virtual DbSet<Vendor> Vendors { get; set; }
}
Here is my controller info:
public IActionResult Index(int id)
{
var thisDepot = _context.Depots.FirstOrDefault(d => d.DepotID == id);
thisDepot.Vendors = _context.Vendors.Join(_context.VendorDepots.Where(d => d.DepotID == id).ToList(),
d => d.VendorID,
d => d.VendorID,
(o, i) => o).ToList();
return View(thisDepot);
}
So the problem I am having is that I can view the specific depot that I select on a new view page but I cannot view the vendors that are associated with the specific depot. I had the code at one point to where I could view all the venders but they weren't specific to the specific depot. Another attempt left me with only viewing vendors that had an id identical to itself, ie.. 1 and 1 or 5 and 5.
Thanks.
Just made some updates, found a misspelling and added some new code for my context and controller files. I really could use some help on the controller!