无法在Entity-Framework Core中创建多表项目

时间:2019-12-19 03:27:08

标签: asp.net-core entity-framework-core

我有一个有效的ASP.NET Web API,我正尝试将其转换为ASP.NET Core。我正在努力添加多表项目。我有以下4个表(SQL Server):

模板, TemplateAction-使用模板的外键, TemplateGroup-带有Template的外键, TemplateCell-具有Template的外键,TemplateAction的外键和TemplateGroup的外键。

enter image description here

添加“模板”(带有一个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.

我尝试了很多事情,但是无法添加模板。谁能看到问题所在吗?谢谢。

1 个答案:

答案 0 :(得分:1)

var cells = new[]
        {
            new TemplateCell
            {
                TemplateGroupId = groups[0].Id,
                TemplateActionId = actions[0].Id,
                IsEnabled = true
            }
        };

当您尝试保存ID时,它们将没有任何价值。

我想你必须要做类似的事情

var cells = new[]
        {
            new TemplateCell
            {
                TemplateGroup = groups[0],
                TemplateAction = actions[0],
                IsEnabled = true
            }
        };

保存引用的对象时,它将为您设置fk。

无论如何,如果您确实希望所有人都对模板有一个fk,那么应该确保您的组/动作/单元指向同一模板,您应该使用复合主键?

还是希望他们可以引用不同的模板?