I have searched on google and stackoverflow for a while and yes I have found many articles on the subject but I still can't seem to know what I am doing wrong.
Problem: I do have a "link" table (many-to-many) between three tables: - check - car - gate
My 'link' class looks like follows:
public class CheckCarGate
{
public int CheckId { get; set; }
public Check Check{ get; set; }
public int CarId { get; set; }
public Car Car{ get; set; }
public int GateId { get; set; }
public Gate Gate { get; set; }
}
DbContext:
public virtual DbSet<Car> Cars{ get; set; }
public virtual DbSet<Gate> Gates { get; set; }
public virtual DbSet<Check> Checks{ get; set; }
// The key:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<CheckCarGate>().HasKey(p => new { p.CheckId, p.CarId, p.GateId });
}
I did follow this documentation https://learn.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many when creating models. CheckCarGate is a navigation property in the entity models. E.g.
public class Gate
{
public int GateId { get; set; }
public string Descr { get; set; }
public ICollection<CheckCarGate> CheckCarGates { get; set; }
}
Code first created this table in the database. Now I'm trying to select all Checks with all Gates for one particular CarId.
I tried something like this:
var masterlist = _context.Checks.Where(p => p.CheckCarGate.Any(x => x.CarId == 12));
or:
var masterlist = _context.Checks
.Include(p => p.CheckCarGate)
.ThenInclude(p=>p.Gate)
.Include(p=>p.CheckCarGate)
.ThenInclude(p=>p.Car);
//Edit: I'm sorry for not giving enough information! Bear with me...
Could someone point me to the right direction?
Many thanks in advance!
N.