简体   繁体   中英

EF Core returning null for many to many

So my use case is pretty simple, I have a vehicle and accessories for the vehicle. Now I have created 3 tables, one for the vehicle, one for the accessory and a many to many table as below: public class Vehicle

Vehicle table

{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string RegistrationNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
    public int Kilometers { get; set; }
    public string VehicleIdentificationNumber { get; set; }
    public decimal RetailPrice { get; set; }
    public decimal CostPrice { get; set; }
    public ICollection<VehicleAccessory> VehicleAccessories { get; set; }
    public ICollection<VehicleImage> VehicleImages { get; set; }
    public DateTime DTCreated { get; set; }
    public DateTime DTUpdated { get; set; }
}

Accessory table

public class Accessory
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Description { get; set; }
    public ICollection<VehicleAccessory> VehicleAccessories { get; set; }
}

Linking table

public class VehicleAccessory
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public long VehicleId { get; set; }
    public Vehicle Vehicle { get; set; }
    public long AccessoryId { get; set; }
    public Accessory Accessory { get; set; }
}

Now I manually added an entry to the db to link the accessory and the vehicle table but it doesn't get recognized if I query the vehicle table to get the VehicleAccessories property, it just returns null. I tried to use include on the property but it gave me a circular reference error. On a side note, I have no idea how to add, using EF, into a many to many table.

To try and get the records I am using: _context.Vehicles.ToList();

Can someone possibly shed some light to why this isn't working.

1) Did you create relationship between these tables in SQL Server?

2) Did you use scaffold-dbcontext command in nuget package console? your VehicleAccessory table looks like that you didn't use scaffold-dbcontext command.

3) Use code below

_context.Vehicles.Include(x => x.VehicleAccessories).Include("VehicleAccessories.Accessory").ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM