我正在尝试创建一个可以从Sql Server DB检索信息的简单RESTful API。我使用.Net Core和EF Core for ORM。
我已经通过外键在我的数据库中映射了两个表。但是,当我尝试在EF核心中实现关系时,似乎BaseStats表中不存在引用Champions表中给定冠军行的行。
在进行API调用时,我得到以下结果:
{
"championId": 1,
"championName": "Vladimir",
"baseStats": null
}
似乎EF核心在某种程度上无法识别这种关系。我一定错过了什么。
任何建议都将不胜感激:)以下是我的代码。提前谢谢。
主要实体:
public class Champion
{
public int ChampionId { get; set; }
public string ChampionName { get; set; }
public ICollection<BaseStat> BaseStats { get; set; }
}
依赖实体
public class BaseStat
{
public int BaseStatId { get; set; }
public int StatTypeId { get; set; }
public decimal Base { get; set; }
public decimal Growth { get; set; }
public Champion Champion { get; set; }
}
数据库上下文
public class Context : DbContext
{
public DbSet<Champion> Champions { get; set; }
public DbSet<BaseStat> BaseStats { get; set; }
public Context(DbContextOptions<Context> options) : base (options)
{
//
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseStat>()
.HasOne(p => p.Champion)
.WithMany(b => b.BaseStats);
}
}
控制器
[Route("api/[controller]/[action]")]
public class ChampionController : Controller
{
private readonly Context _context;
public ChampionController(Context context)
{
_context = context;
}
public async Task<JsonResult> Stats()
{
var champ = await _context.Champions.FirstOrDefaultAsync(c => c.ChampionId == 1);
return Json(champ);
}
}
答案 0 :(得分:0)
我根据Ivan Stoev的回答更新了控制器中的统计数据操作。
public async Task<JsonResult> Stats()
{
Champion champion = await _context.Champions
.Include(c => c.BaseStats)
.FirstOrDefaultAsync();
return Json(champion);
}
当动作返回正确的信息时,当我通过浏览器进行API调用时,它似乎继续加载,好像呼叫没有结束。 (浏览器标签中的微调器,谷歌浏览器)
与此同时,我无法在Postman中进行API调用,而不会出现以下错误:
Could not get any response
There was an error connecting to http://localhost:50185/api/champion/stats.
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
Client certificates are required for this server:
Fix this by adding client certificates in Settings > Certificates
Request timeout:
Change request timeout in Settings > General
有没有人知道可能导致这种情况的原因?