简体   繁体   English

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

[英]EF Core 3.0 adding connected entity to collection fails in One To Many relationship

I try to add entity through the navigation property of collection, but the following message comes up: 我尝试通过collection的navigation属性添加实体,但是出现以下消息:

"Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions." “数据库操作预期会影响1行,但实际上会影响0行。自从加载实体以来,数据可能已经被修改或删除。有关的信息,请参见http://go.microsoft.com/fwlink/?LinkId=527962(页面可能为英文)。有关了解和处理乐观并发异常的信息。”

The models are: 这些模型是:

SuggestionGroupDb: RecommendationGroupDb:

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: RecommendationionItemDb:

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 Repository Update function (simplified): 建议组存储库更新功能(已简化):

    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);
        }
    }

The problem is that SaveChanges throws and exception with the given message. 问题在于,SaveChanges会引发给定消息并发生异常。 Is it possible to update the SuggestionItems through the SuggestionGroup? 是否可以通过意见建议组更新意见建议项?

I am using EF Core 3.0 preview 6. 我正在使用EF Core 3.0预览版6。

Prior to EF Core 3.0, untracked entities discovered by the DetectChanges strategy (in your case, by adding an untracked entity to a collection) would automatically be in the Added state. 在EF Core 3.0之前,通过DetectChanges策略发现的未跟踪实体(在您的情况下,是通过将未跟踪实体添加到集合中)将自动处于“已Added状态。

This is no longer the case. 这已不再是这种情况。 From Entity Framework Core 3.0 the entity will be automatically added in the Modified state. 从Entity Framework Core 3.0开始,该实体将自动以“已Modified状态添加。

Why 为什么

This change was made to make it easier and more consistent to work with disconnected entity graphs while using store-generated keys. 进行此更改是为了在使用商店生成的键时更轻松,更一致地使用断开的实体图。

Source: EF Core 3.0 - Breaking Changes 资料来源: EF Core 3.0-重大变化

You can force new untracked entities to be added in the Added state by configuring the key property to explicitly not use generated values. 您可以通过将key属性配置为显式不使用生成的值来强制将新的未跟踪实体添加为“已Added状态。

For example: 例如:

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

Or using the fluent API 或使用流畅的API

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM