我正在使用.NET 6和Entity Framework Core构建Web API,以连接到SQL Server数据库。基本的东西看起来工作正常,但我无法使我的模型中的多对多关系工作。
考虑以下3个表: 产品:
我创建了以下的
当我使用Swagger运行项目时,调用检索产品的端点时会得到以下结果:
因此,端点正在工作并从数据库检索产品。
但是,由于某种原因,它没有与类别建立关系(是的,我确定在ProductCategory表中有记录来定义产品和类别之间的关系)。我确定我缺少了什么,但我不知道我缺少了什么。有人可以指导我如何使其正常工作吗?
考虑以下3个表: 产品:
分类:
产品类别:
我已经创建了三个与这些表相对应的模型,如下所示:public class Product
{
[Key]
public int Id { get; set; } = 0;
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Label { get; set; } = string.Empty;
public int Sativa { get; set; } = 0;
public int Indica { get; set; } = 0;
public ICollection<CategoryProduct> Categories { get; set; } = new HashSet<CategoryProduct>();
}
public class Category
{
[Key]
public int Id { get; set; } = 0;
public string Name { get; set; } = string.Empty;
public int Order { get; set; } = 0;
public ICollection<CategoryProduct> Products { get; set; } = new HashSet<CategoryProduct>();
}
public class CategoryProduct
{
public int CategoryId { get; set; } = 0;
public Category? Category { get; set; } = null;
public int ProductId { get; set; } = 0;
public Product? Product { get; set; } = null;
}
我创建了以下的
DbContext
类来与数据库通信:public class CoffeeshopContext : DbContext
{
public DbSet<Shop>? Shops { get; set; } = null;
public DbSet<Category>? Categories { get; set; } = null;
public DbSet<Product>? Products { get; set; } = null;
public DbSet<Price>? Prices { get; set; } = null;
public DbSet<CategoryProduct>? ProductCategories { get; set; } = null;
private readonly IConfiguration _configuration;
public CoffeeshopContext(DbContextOptions<CoffeeshopContext> options, IConfiguration configuration) : base(options)
{
_configuration = configuration;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CategoryProduct>().HasKey(x => new { x.CategoryId, x.ProductId });
modelBuilder.Entity<CategoryProduct>().HasOne(x => x.Product)
.WithMany(x => x.Categories)
.HasForeignKey(x => x.ProductId);
modelBuilder.Entity<CategoryProduct>().HasOne(x => x.Category)
.WithMany(x => x.Products)
.HasForeignKey(x => x.CategoryId);
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(nameof(CoffeeshopContext)));
}
}
当我使用Swagger运行项目时,调用检索产品的端点时会得到以下结果:
[
{
"id": 3,
"name": "Ice Cream Bean",
"description": "Well balanced hybrid with a mood boosting euphoric high and body relaxation. Diesel and citrus aroma with creamy fruity undertones.",
"label": "CALI STRAIN",
"sativa": 50,
"indica": 50,
"categories": []
},
{
"id": 4,
"name": "Blue Cheese",
"description": "Deep relaxing, calming and pain relief. Berry, blue cheese aroma and a creamy taste.",
"label": "CLASSIC STRAIN",
"sativa": 20,
"indica": 80,
"categories": []
}
]
因此,端点正在工作并从数据库检索产品。
但是,由于某种原因,它没有与类别建立关系(是的,我确定在ProductCategory表中有记录来定义产品和类别之间的关系)。我确定我缺少了什么,但我不知道我缺少了什么。有人可以指导我如何使其正常工作吗?