简体   繁体   English

EF Core 为多对多返回 null

[英]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现在我创建了 3 个表,一个用于车辆,一个用于附件,还有一个多对多表,如下所示:

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.现在我手动向数据库添加了一个条目以链接附件和车辆表,但是如果我查询车辆表以获取 VehicleAccessories 属性,它不会被识别,它只返回空值。 I tried to use include on the property but it gave me a circular reference error.我试图在属性上使用 include ,但它给了我一个循环引用错误。 On a side note, I have no idea how to add, using EF, into a many to many table.附带说明一下,我不知道如何使用 EF 添加到多对多表中。

To try and get the records I am using: _context.Vehicles.ToList();尝试获取我正在使用的记录: _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? 1)您是否在 SQL Server 中创建了这些表之间的关系?

2) Did you use scaffold-dbcontext command in nuget package console? 2) 您是否在 nuget 包控制台中使用了 scaffold-dbcontext 命令? your VehicleAccessory table looks like that you didn't use scaffold-dbcontext command.您的 VehicleAccessory 表看起来像您没有使用 scaffold-dbcontext 命令。

3) Use code below 3)使用下面的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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