EF Core 3.0将连接的实体添加到集合中时,一对多关系失败

时间:2019-09-13 12:12:42

标签: c# asp.net-core repository ef-core-3.0

我尝试通过collection的navigation属性添加实体,但是出现以下消息:

“数据库操作预期会影响1行,但实际上会影响0行。自从加载实体以来,数据可能已被修改或删除。有关了解和处理乐观并发异常的信息,请参见http://go.microsoft.com/fwlink/?LinkId=527962 。”

模型是:

SuggestionGroupDb:

public class SuggestionGroupDb
{
    public Guid Id { get; set; }

    [Required]
    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual TeguUserDb User { get; set; }

    [Required(AllowEmptyStrings=false, ErrorMessage = "Required")]
    [StringLength(30, MinimumLength = 1, ErrorMessage = "Invalid")]
    public string Name { get; set; }

    public int OrderNo { get; set; }

    public virtual ICollection<SuggestionItemDb> Items { get; set; }
}

SuggestionItemDb:

public class SuggestionItemDb
{
    public Guid Id { get; set; }

    [Required]
    public Guid SuggestionGroupId { get; set; }
    [ForeignKey("SuggestionGroupId")]
    public virtual SuggestionGroupDb SuggestionGroup { get; set; }

    [Required(AllowEmptyStrings=false, ErrorMessage = "Required")]
    [StringLength(30, MinimumLength = 1, ErrorMessage = "Invalid")]
    public string Name { get; set; }

    public int OrderNo { get; set; }
}

SuggestionGroup存储库更新功能(简化):

    public async Task<SuggestionGroupRepositoryResult> UpdateAsync(string userid, SuggestionGroupDb suggestiongroup)
    {
        // Step 01 - Get the Entity
        var dbSuggestionGroup = await GetAsync(userid, suggestiongroup.Id, suggestiongroup.Name);

        // Step 02 - Update the items (just add one now)
        foreach (var item in suggestiongroup.Items)
        {
            var sidb = new SuggestionItemDb() {Id = item.Id, Name = item.Name, OrderNo = item.OrderNo, SuggestionGroupId = item.SuggestionGroupId};
            dbSuggestionGroup .Items.Add(sidb);
        }

        // Step 03 - Update the changes
        try
        {
            var updated = context.AccSuggestionGroups.Update(dbSuggestionGroup);
            await context.SaveChangesAsync();

            return new SuggestionGroupRepositoryResult("Valid") /*{SuggestionGroup = updated.Entity}*/;
        }
        catch (Exception e)
        {
            context.Reset();
            return new SuggestionGroupRepositoryResult("Failed", e.Message);
        }
    }

问题在于,SaveChanges会抛出异常,并且出现给定的消息。 是否可以通过uggestinationgroup更新suggestionItems?

我正在使用EF Core 3.0预览版6。

1 个答案:

答案 0 :(得分:2)

在EF Core 3.0之前,通过DetectChanges策略发现的未跟踪实体(在您的情况下,通过将未跟踪实体添加到集合中)将自动处于Added状态。

情况不再如此。从Entity Framework Core 3.0开始,该实体将自动以Modified状态添加。

  

为什么

     

进行此更改是为了在使用商店生成的键时更轻松,更一致地使用断开的实体图。

     

来源:EF Core 3.0 - Breaking Changes

您可以通过将key属性配置为显式不使用生成的值来强制以Added状态添加新的未跟踪实体。

例如:

public class SuggestionItemDb
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid Id { get; set; }
}

或使用流畅的API

modelBuilder
    .Entity<SuggestionItemDb>()
    .Property(e => e.Id)
    .ValueGeneratedNever();