【发布时间】:2019-12-19 03:27:08
【问题描述】:
我有一个可用的 ASP.NET Web API,我正在尝试将其转换为 ASP.NET Core。我正在努力添加多表项目。我有以下 4 个表(SQL Server):
模板, TemplateAction - 带有模板的外键, TemplateGroup - 具有模板的外键, TemplateCell - 具有 Template 的外键、TemplateAction 的外键和 TemplateGroup 的外键。
添加“模板”(一个TemplateAction,一个TemplateGroup,一个TemplateCell)的代码如下:
public async Task<int> CreateTemplate(string userId, TemplateCreateDTO dto)
{
using (var context = MyDataContext.Instance) // Injected in ASP.NET Core (no using)
{
var now = DateTime.UtcNow;
// Create s single default Group
var groups = new[]
{
new TemplateGroup
{
Name = "Row Name",
Description = string.Empty,
SortOrder = 0
}
};
// Create s single default Action
var actions = new[]
{
new TemplateAction
{
Name = "Column Name",
Description = string.Empty,
SortOrder = 0
}
};
// All cells are enabled when a Template is created
var cells = new[]
{
new TemplateCell
{
TemplateGroupId = groups[0].Id,
TemplateActionId = actions[0].Id,
IsEnabled = true
}
};
var template = new Template
{
Name = dto.Name,
Description = dto.Description,
InitialRisk = dto.InitialRisk,
CreatedWhen = now,
CreatedByUserId = userId,
ModifiedWhen = now,
ModifiedByUserId = userId,
TemplateGroups = groups,
TemplateActions = actions,
TemplateCells = cells
};
context.Templates
.Add(template);
await context.SaveChangesAsync();
return template.Id;
}
}
ASP.NET Core 3.1 (EF Core 3.1) 中的相同代码 - 除了上下文被注入 - 失败并出现以下错误:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_TemplateCell_TemplateAction\". The conflict occurred in database \"MyDB\", table \"dbo.TemplateAction\", column 'Id'.\r\nThe statement has been terminated.
我尝试了很多东西,但无法添加模板。谁能看到问题可能是什么?谢谢。
【问题讨论】:
标签: asp.net-core entity-framework-core