EF Core 3.0在一对多关系中将连接的实体添加到集合中失败 [英] EF Core 3.0 adding connected entity to collection fails in One To Many relationship

查看:271
本文介绍了EF Core 3.0在一对多关系中将连接的实体添加到集合中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to add entity through the navigation property of collection, but the following message comes up:

数据库操作预期会影响1行,但实际上会影响0行.自加载实体以来,数据可能已被修改或删除.请参见

"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."

模型是:

SuggestionGroupDb:

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:

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存储库更新功能(简化):

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

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

The problem is that SaveChanges throws and exception with the given message. Is it possible to update the SuggestionItems through the SuggestionGroup?

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

I am using EF Core 3.0 preview 6.

推荐答案

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

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.

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

This is no longer the case. From Entity Framework Core 3.0 the entity will be automatically added in the Modified state.

为什么

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

This change was made to make it easier and more consistent to work with disconnected entity graphs while using store-generated keys.

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

You can force new untracked entities to be added in the Added state by configuring the key property to explicitly not use generated values.

例如:

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

或使用流畅的API

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

这篇关于EF Core 3.0在一对多关系中将连接的实体添加到集合中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆