Entity Framework Core 2.1无法更新具有关系的实体

时间:2018-07-02 13:27:04

标签: c# entity-framework-core asp.net-core-webapi

我目前在EF核心2.1和本机客户端用来更新包含多个级别嵌入式对象的对象的Web API方面遇到问题。 我已经阅读了这两个主题:

Entity Framework Core: Fail to update Entity with nested value objects

https://docs.microsoft.com/en-us/ef/core/saving/disconnected-entities

我已经了解到,在EF Core 2中更新对象确实不是很明显,但是我还没有找到一种可行的解决方案。 每次尝试时,我都会遇到一个例外,告诉我EF已经跟踪了“步骤”。

我的模型如下:

//CIApplication the root class I’m trying to update
public class CIApplication : ConfigurationItem // -> derive of BaseEntity which holds the ID and some other properties  
{

    //Collection of DeploymentScenario
    public virtual ICollection<DeploymentScenario> DeploymentScenarios { get; set; }

    //Collection of SoftwareMeteringRules
    public virtual ICollection<SoftwareMeteringRule> SoftwareMeteringRules { get; set; }
}

//部署场景,与应用程序具有一对多的关系。部署方案包含两个步骤列表

public class DeploymentScenario : BaseEntity
{

    //Collection of substeps
    public virtual ICollection<Step> InstallSteps { get; set; }
    public virtual ICollection<Step> UninstallSteps { get; set; }

    //Navigation properties Parent CI
    public Guid? ParentCIID { get; set; }
    public virtual CIApplication ParentCI { get; set; }
}

// Step,它也很复杂并且也是自引用的

public class Step : BaseEntity
{

    public string ScriptBlock { get; set; }


    //Parent Step Navigation property
    public Guid? ParentStepID { get; set; }
    public virtual Step ParentStep { get; set; }

    //Parent InstallDeploymentScenario Navigation property
    public Guid? ParentInstallDeploymentScenarioID { get; set; }
    public virtual DeploymentScenario ParentInstallDeploymentScenario { get; set; }

    //Parent InstallDeploymentScenario Navigation property
    public Guid? ParentUninstallDeploymentScenarioID { get; set; }
    public virtual DeploymentScenario ParentUninstallDeploymentScenario { get; set; }

    //Collection of sub steps
    public virtual ICollection<Step> SubSteps { get; set; }

    //Collection of input variables
    public virtual List<ScriptVariable> InputVariables { get; set; }
    //Collection of output variables
    public virtual List<ScriptVariable> OutPutVariables { get; set; }

}

这是我的更新方法,我知道它很丑陋,不应该放在控制器中,但是我每两个小时都要更改一次,因为我尝试在网上找到解决方案。 这是最后一次迭代来自 https://docs.microsoft.com/en-us/ef/core/saving/disconnected-entities

public async Task<IActionResult> PutCIApplication([FromRoute] Guid id, [FromBody] CIApplication cIApplication)
    {
        _logger.LogWarning("Updating CIApplication " + cIApplication.Name);

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != cIApplication.ID)
        {
            return BadRequest();
        }

        var cIApplicationInDB = _context.CIApplications
            .Include(c => c.Translations)
            .Include(c => c.DeploymentScenarios).ThenInclude(d => d.InstallSteps).ThenInclude(s => s.SubSteps)
            .Include(c => c.DeploymentScenarios).ThenInclude(d => d.UninstallSteps).ThenInclude(s => s.SubSteps)
            .Include(c => c.SoftwareMeteringRules)
            .Include(c => c.Catalogs)
            .Include(c => c.Categories)
            .Include(c => c.OwnerCompany)
            .SingleOrDefault(c => c.ID == id);

        _context.Entry(cIApplicationInDB).CurrentValues.SetValues(cIApplication);

        foreach(var ds in cIApplication.DeploymentScenarios)
        {
            var existingDeploymentScenario = cIApplicationInDB.DeploymentScenarios.FirstOrDefault(d => d.ID == ds.ID);

            if (existingDeploymentScenario == null)
            {
                cIApplicationInDB.DeploymentScenarios.Add(ds);
            }
            else
            {
                _context.Entry(existingDeploymentScenario).CurrentValues.SetValues(ds);

                foreach(var step in existingDeploymentScenario.InstallSteps)
                {
                    var existingStep = existingDeploymentScenario.InstallSteps.FirstOrDefault(s => s.ID == step.ID);

                    if (existingStep == null)
                    {
                        existingDeploymentScenario.InstallSteps.Add(step);
                    }
                    else
                    {
                        _context.Entry(existingStep).CurrentValues.SetValues(step);
                    }
                }
            }
        }
        foreach(var ds in cIApplicationInDB.DeploymentScenarios)
        {
            if(!cIApplication.DeploymentScenarios.Any(d => d.ID == ds.ID))
            {
                _context.Remove(ds);
            }
        }

        //_context.Update(cIApplication);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException e)
        {
            if (!CIApplicationExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        catch(Exception e)
        {
        }

        return Ok(cIApplication);
    }

到目前为止,我遇到了这个异常: 无法跟踪实体类型“ Step”的实例,因为已经跟踪了具有键值“ {ID:e29b3c1c-2e06-4c7b-b0cd-f8f1c5ccb7b6}”的另一个实例。

我注意到客户端以前没有进行过“ get”操作,即使是在我的get方法上放置了AsNoTracking的情况。 如果我应该添加新记录或更新现有记录,客户端将在更新之前进行的唯一操作是“ _context.CIApplications.Any(e => e.ID == id);”。

几天以来,我一直在努力解决这个问题,因此,如果有人可以帮助我朝正确的方向发展,我将不胜感激。 非常感谢

更新:

我在控制器中添加了以下代码:

var existingStep = existingDeploymentScenario.InstallSteps.FirstOrDefault(s => s.ID == step.ID);
                    entries = _context.ChangeTracker.Entries();
                    if (existingStep == null)
                    {
                        existingDeploymentScenario.InstallSteps.Add(step);
                        entries = _context.ChangeTracker.Entries();
                    }

条目= _context.ChangeTracker.Entries();在添加包含新步骤的新DeploymentScenario之后,立即引发“已跟踪步骤”异常。

在此之前,新的DeploymentScenario和step不在跟踪器中,并且我已经在数据库中检查了它们的ID是否重复。

我也检查了我的Post方法,现在它也失败了...我将其恢复为默认方法,里面没有花哨的东西:

[HttpPost]
    public async Task<IActionResult> PostCIApplication([FromBody] CIApplication cIApplication)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var entries = _context.ChangeTracker.Entries();
        _context.CIApplications.Add(cIApplication);
        entries = _context.ChangeTracker.Entries();
        await _context.SaveChangesAsync();
        entries = _context.ChangeTracker.Entries();
        return CreatedAtAction("GetCIApplication", new { id = cIApplication.ID }, cIApplication);
    }

条目开头是空的,_context.CIApplications.Add(cIApplication);生产线仍在引发异常,仍然是部署场景中仅包含的一个步骤...

因此,当我尝试在自己的上下文中添加内容时,显然存在某些错误,但是现在我感到完全迷失了。这可能有助于我在启动时声明上下文:

services.AddDbContext<MyAppContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
            b => b.MigrationsAssembly("DeployFactoryDataModel")),
            ServiceLifetime.Transient
            );

添加我的上下文类:

public class MyAppContext : DbContext
{
    private readonly IHttpContextAccessor _contextAccessor;
    public MyAppContext(DbContextOptions<MyAppContext> options, IHttpContextAccessor contextAccessor) : base(options)
    {
        _contextAccessor = contextAccessor;
    }


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        optionsBuilder.EnableSensitiveDataLogging();
    }

    public DbSet<Step> Steps { get; set; }
    //public DbSet<Sequence> Sequences { get; set; }
    public DbSet<DeploymentScenario> DeploymentScenarios { get; set; }
    public DbSet<ConfigurationItem> ConfigurationItems { get; set; }
    public DbSet<CIApplication> CIApplications { get; set; }
    public DbSet<SoftwareMeteringRule> SoftwareMeteringRules { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<ConfigurationItemCategory> ConfigurationItemsCategories { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<Catalog> Catalogs { get; set; }
    public DbSet<CIDriver> CIDrivers { get; set; }
    public DbSet<DriverCompatiblityEntry> DriverCompatiblityEntries { get; set; }
    public DbSet<ScriptVariable> ScriptVariables { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Step one to many with step for sub steps
        modelBuilder.Entity<Step>().HasMany(s => s.SubSteps).WithOne(s => s.ParentStep).HasForeignKey(s => s.ParentStepID);

        //Step one to many with step for variables
        modelBuilder.Entity<Step>().HasMany(s => s.InputVariables).WithOne(s => s.ParentInputStep).HasForeignKey(s => s.ParentInputStepID);
        modelBuilder.Entity<Step>().HasMany(s => s.OutPutVariables).WithOne(s => s.ParentOutputStep).HasForeignKey(s => s.ParentOutputStepID);

        //Step one to many with sequence
        //modelBuilder.Entity<Step>().HasOne(step => step.ParentSequence).WithMany(seq => seq.Steps).HasForeignKey(step => step.ParentSequenceID).OnDelete(DeleteBehavior.Cascade);

        //DeploymentScenario One to many with install steps
        modelBuilder.Entity<DeploymentScenario>().HasMany(d => d.InstallSteps).WithOne(s => s.ParentInstallDeploymentScenario).HasForeignKey(s => s.ParentInstallDeploymentScenarioID);

        //DeploymentScenario One to many with uninstall steps
        modelBuilder.Entity<DeploymentScenario>().HasMany(d => d.UninstallSteps).WithOne(s => s.ParentUninstallDeploymentScenario).HasForeignKey(s => s.ParentUninstallDeploymentScenarioID);

        //DeploymentScenario one to one with sequences
        //modelBuilder.Entity<DeploymentScenario>().HasOne(ds => ds.InstallSequence).WithOne(seq => seq.IDeploymentScenario).HasForeignKey<DeploymentScenario>(ds => ds.InstallSequenceID).OnDelete(DeleteBehavior.Cascade);
        //modelBuilder.Entity<DeploymentScenario>().HasOne(ds => ds.UninstallSequence).WithOne(seq => seq.UDeploymentScenario).HasForeignKey<DeploymentScenario>(ds => ds.UninstallSequenceID);

        //Step MUI config
        modelBuilder.Entity<Step>().Ignore(s => s.Description);
        modelBuilder.Entity<Step>().HasMany(s => s.Translations).WithOne().HasForeignKey(x => x.StepTranslationId);

        //Sequence MUI config
        //modelBuilder.Entity<Sequence>().Ignore(s => s.Description);
        //modelBuilder.Entity<Sequence>().HasMany(s => s.Translations).WithOne().HasForeignKey(x => x.SequenceTranslationId);

        //DeploymentScenario MUI config
        modelBuilder.Entity<DeploymentScenario>().Ignore(s => s.Name);
        modelBuilder.Entity<DeploymentScenario>().Ignore(s => s.Description);
        modelBuilder.Entity<DeploymentScenario>().HasMany(s => s.Translations).WithOne().HasForeignKey(x => x.DeploymentScenarioTranslationId);

        //CIApplication  relations
        //CIApplication one to many relation with Deployment Scenario
        modelBuilder.Entity<CIApplication>().HasMany(ci => ci.DeploymentScenarios).WithOne(d => d.ParentCI).HasForeignKey(d => d.ParentCIID).OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<CIApplication>().HasMany(ci => ci.SoftwareMeteringRules).WithOne(d => d.ParentCI).HasForeignKey(d => d.ParentCIID).OnDelete(DeleteBehavior.Cascade);

        // CIDriver relations
        // CIAPpplication one to many relation with DriverCompatibilityEntry
        modelBuilder.Entity<CIDriver>().HasMany(ci => ci.CompatibilityList).WithOne(c => c.ParentCI).HasForeignKey(c => c.ParentCIID).OnDelete(DeleteBehavior.Restrict);

        //ConfigurationItem MUI config
        modelBuilder.Entity<ConfigurationItem>().Ignore(s => s.Name);
        modelBuilder.Entity<ConfigurationItem>().Ignore(s => s.Description);
        modelBuilder.Entity<ConfigurationItem>().HasMany(s => s.Translations).WithOne().HasForeignKey(x => x.ConfigurationItemTranslationId);

        //category MUI config
        modelBuilder.Entity<Category>().Ignore(s => s.Name);
        modelBuilder.Entity<Category>().Ignore(s => s.Description);
        modelBuilder.Entity<Category>().HasMany(s => s.Translations).WithOne().HasForeignKey(x => x.CategoryTranslationId);

        //CI Categories Many to Many
        modelBuilder.Entity<ConfigurationItemCategory>().HasKey(cc => new { cc.CategoryId, cc.CIId });
        modelBuilder.Entity<ConfigurationItemCategory>().HasOne(cc => cc.Category).WithMany(cat => cat.ConfigurationItems).HasForeignKey(cc => cc.CategoryId);
        modelBuilder.Entity<ConfigurationItemCategory>().HasOne(cc => cc.ConfigurationItem).WithMany(ci => ci.Categories).HasForeignKey(cc => cc.CIId);

        //CI Catalog Many to Many
        modelBuilder.Entity<CICatalog>().HasKey(cc => new { cc.CatalogId, cc.ConfigurationItemId });
        modelBuilder.Entity<CICatalog>().HasOne(cc => cc.Catalog).WithMany(cat => cat.CIs).HasForeignKey(cc => cc.CatalogId);
        modelBuilder.Entity<CICatalog>().HasOne(cc => cc.ConfigurationItem).WithMany(ci => ci.Catalogs).HasForeignKey(cc => cc.ConfigurationItemId);

        //Company Customers Many to Many
        modelBuilder.Entity<CompanyCustomers>().HasKey(cc => new { cc.CustomerId, cc.ProviderId });
        modelBuilder.Entity<CompanyCustomers>().HasOne(cc => cc.Provider).WithMany(p => p.Customers).HasForeignKey(cc => cc.ProviderId).OnDelete(DeleteBehavior.Restrict);
        modelBuilder.Entity<CompanyCustomers>().HasOne(cc => cc.Customer).WithMany(c => c.Providers).HasForeignKey(cc => cc.CustomerId);

        //Company Catalog Many to Many
        modelBuilder.Entity<CompanyCatalog>().HasKey(cc => new { cc.CatalogId, cc.CompanyId });
        modelBuilder.Entity<CompanyCatalog>().HasOne(cc => cc.Catalog).WithMany(c => c.Companies).HasForeignKey(cc => cc.CatalogId);
        modelBuilder.Entity<CompanyCatalog>().HasOne(cc => cc.Company).WithMany(c => c.Catalogs).HasForeignKey(cc => cc.CompanyId);

        //Author Catalog Many to Many
        modelBuilder.Entity<CatalogAuthors>().HasKey(ca => new { ca.AuthorId, ca.CatalogId });
        modelBuilder.Entity<CatalogAuthors>().HasOne(ca => ca.Catalog).WithMany(c => c.Authors).HasForeignKey(ca => ca.CatalogId);
        modelBuilder.Entity<CatalogAuthors>().HasOne(ca => ca.Author).WithMany(a => a.AuthoringCatalogs).HasForeignKey(ca => ca.AuthorId);

        //Company one to many with owned Catalog
        modelBuilder.Entity<Company>().HasMany(c => c.OwnedCatalogs).WithOne(c => c.OwnerCompany).HasForeignKey(c => c.OwnerCompanyID).OnDelete(DeleteBehavior.Restrict);
        //Company one to many with owned Categories
        modelBuilder.Entity<Company>().HasMany(c => c.OwnedCategories).WithOne(c => c.OwnerCompany).HasForeignKey(c => c.OwnerCompanyID).OnDelete(DeleteBehavior.Restrict);
        //Company one to many with owned CIs
        modelBuilder.Entity<Company>().HasMany(c => c.OwnedCIs).WithOne(c => c.OwnerCompany).HasForeignKey(c => c.OwnerCompanyID).OnDelete(DeleteBehavior.Restrict);

        //CIDriver one to many with DriverCompatibilityEntry
        modelBuilder.Entity<CIDriver>().HasMany(c => c.CompatibilityList).WithOne(c => c.ParentCI).HasForeignKey(c => c.ParentCIID).OnDelete(DeleteBehavior.Restrict);

        //User Group Many to Many
        modelBuilder.Entity<UserGroup>().HasKey(ug => new { ug.UserId, ug.GroupId });
        modelBuilder.Entity<UserGroup>().HasOne(cg => cg.User).WithMany(ci => ci.Groups).HasForeignKey(cg => cg.UserId);
        modelBuilder.Entity<UserGroup>().HasOne(cg => cg.Group).WithMany(ci => ci.Users).HasForeignKey(cg => cg.GroupId);

        //User one to many with Company
        modelBuilder.Entity<Company>().HasMany(c => c.Employees).WithOne(u => u.Employer).HasForeignKey(u => u.EmployerID).OnDelete(DeleteBehavior.Restrict);
    }

更新2

这是一个指向极简复制示例的驱动器链接。我尚未在客户端中实现PUT,因为post方法已经重现了问题。

https://1drv.ms/u/s!AsO87EeN0Fnsk7dDRY3CJeeLT-4Vag

2 个答案:

答案 0 :(得分:3)

您将在此处枚举现有步骤,并在没有意义的现有步骤集合中搜索现有步骤。

 foreach(var step in existingDeploymentScenario.InstallSteps)
     var existingStep = existingDeploymentScenario.InstallSteps
         .FirstOrDefault(s => s.ID == step.ID);

它可能应该是:

foreach(var step in ds.InstallSteps)

答案 1 :(得分:1)

我想通了,我感到很ham愧。

感谢大家,我最终怀疑客户端及其处理数据的原因。

事实证明,当客户端创建部署方案时,它会创建一个步骤并将其分配到installStep和uninstallSteps列表中,从而导致问题...

我非常确定未使用卸载步骤列表,甚至在调试时都没有浏览过它。