我遇到了一个问题,正在设置Entity Framework Core和Asp .NET Core中的简单多对多关系,这让我很疯狂。每当我尝试使用
以下是Product和Category类之间的简单关系示例:
然而,取消注释Get方法中的Includes调用会导致以下结果:
无法获取任何响应。
Includes()
方法返回相关集合时,我的HTTP响应就会出错。能否有人帮我解决一下?以下是Product和Category类之间的简单关系示例:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<ProductCategory> ProductCategories { get; set; }
}
public class ProductCategory
{
public int ProductId { get; set; }
public int CategoryId { get; set; }
public Product Product { get; set; }
public Category Category { get; set; }
}
同时还有Entity Framework DbContext:
public class ProductDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductCategory>().HasKey(s => new { s.ProductId, s.CategoryId });
base.OnModelCreating(modelBuilder);
}
}
这里有一个控制器,带有一个Set方法(快速填充数据的方式),以及一个Get方法来获取结果:
public class ProductController : Controller
{
ProductDbContext _context;
public ProductController(ProductDbContext context)
{
_context = context;
}
public IActionResult Set()
{
_context.Products.AddRange(
new Product
{
Name = "TestProduct1"
},
new Product
{
Name = "TestProduct2"
}
);
_context.Categories.AddRange(
new Category
{
Name = "TestCategory1"
},
new Category
{
Name = "TestCategory2"
}
);
_context.SaveChanges();
_context.ProductCategories.AddRange(
new ProductCategory
{
ProductId = 1,
CategoryId = 1
},
new ProductCategory
{
ProductId = 2,
CategoryId = 1
},
new ProductCategory
{
ProductId = 2,
CategoryId = 2
}
);
_context.SaveChanges();
return Ok();
}
public IActionResult Get()
{
var products = _context.Products
//.Include(p => p.ProductCategories)
.ToList();
return Ok(products);
}
}
为了进行测试,我首先通过Postman访问Set方法(http://localhost:54551/product/set)。之后,访问Get方法(http://localhost:54551/product/get)会返回以下内容:
[
{
"productId": 1,
"name": "TestProduct1",
"productCategories": null
},
{
"productId": 2,
"name": "TestProduct2",
"productCategories": null
}
]
然而,取消注释Get方法中的Includes调用会导致以下结果:
无法获取任何响应。
There was an error connecting to http://localhost:54551/product/get.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General
我缺少什么?我已经设置了CORS以允许任何来源。如果我在return Ok(products)
上设置断点,并取消注释Includes()
调用,我可以看到数据被添加到products
对象中。
为什么响应会失败?