我有一个工作的ASP.NET网络应用程序接口,我正在尝试转换为ASP.NET核心。我正在为一个多表项目添加而苦苦挣扎。我有以下4个表(SQL Server):
模板,TemplateAction -模板的外键,TemplateGroup -模板的外键,TemplateCell -模板的外键,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核心3.1 (EF核心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.我已经尝试了很多东西,但一直无法添加模板。有没有人能看到问题出在哪里?谢谢。
发布于 2019-12-19 11:37:58
var cells = new[]
{
new TemplateCell
{
TemplateGroupId = groups[0].Id,
TemplateActionId = actions[0].Id,
IsEnabled = true
}
};当您尝试保存时,ids将没有任何值。
我猜你必须做这样的事情
var cells = new[]
{
new TemplateCell
{
TemplateGroup = groups[0],
TemplateAction = actions[0],
IsEnabled = true
}
};保存被引用的对象时,它会将fk设置为您。
无论如何,你可以看到,为了确保你的组/操作/单元格指向相同的模板,如果你真的想让所有的模板都有一个fk,那么你应该使用一个复合主键,对吧?
或者期望它们可以引用不同的模板?
https://stackoverflow.com/questions/59402933
复制相似问题