如何在EF Core上更新自有类型

时间:2017-12-17 14:07:04

标签: c# ef-core-2.0

我有这些课程

public class ProcessExecution : AggregateRoot
{
    public Guid ParticipantId { get; protected set; }

    public Guid ProcessId { get; protected set; }

    public Process.Process Process { get; protected set; }

    public ICollection<ArtifactExecution> Executions { get; protected set; }
}

public class ArtifactExecution : Entity<Guid>
{
    public ProcessArtifact Artifact { get; set; }
    public Guid ArtifactId { get; set; }

    public Guid ExecutionId { get; protected set; }
    public ProcessExecution Execution { get; protected set; }

    public ArtifactExecutionStatus ExecutionStatus { get; protected set; }
}

public class ArtifactExecutionStatus : ValueObject<ArtifactExecutionStatus>
{
    public string Status { get; protected set; }

    protected ArtifactExecutionStatus()
    {

    }

    public ArtifactExecutionStatus(string status)
    {
        Status = status;
    }
}

这是ef映射

class ProcessExecutionMap : IEntityTypeConfiguration<Workflow.Domain.Execution.ProcessExecution>
{
    public void Configure(EntityTypeBuilder<Workflow.Domain.Execution.ProcessExecution> builder)
    {
        builder.HasKey(x => x.Id);

        builder.Property(x => x.ParticipantId)
            .IsRequired();

        builder.HasOne(x => x.Process)
            .WithMany(x => x.Executions)
            .HasForeignKey(x => x.ProcessId);

        builder.HasMany(x => x.Executions)
            .WithOne(x => x.Execution)
            .HasForeignKey(x => x.ExecutionId);

        builder.Ignore(x => x.Events);
    }
}

class ArtifactExecutionMap : IEntityTypeConfiguration<ArtifactExecution>
{
    public void Configure(EntityTypeBuilder<ArtifactExecution> builder)
    {
        builder.HasKey(x => x.Id);

        builder.HasOne(x => x.Execution)
            .WithMany(x => x.Executions)
            .HasForeignKey(x => x.ExecutionId);

        builder.HasOne(x => x.Artifact)
            .WithMany(x => x.Executions)
            .HasForeignKey(x => x.ArtifactId);

        builder.OwnsOne(x => x.ExecutionStatus, ob =>
        {
            ob.ToTable(nameof(ArtifactExecution));
            ob.Property(x => x.Status)
                .IsRequired()
                .HasColumnName("Status")
                .HasColumnType("varchar(50)");
        });
    }
}

这里的目标是使用值对象使用一些DDD aproach。 当我需要保存聚合时,一切正常。

现在,在我的模型中,有时我需要执行这样的事情。

ExecutionStatus = new ArtifactExecutionStatus("FINISHED");

当我需要更新时,我得到了这个例外。

  

执行请求时发生了未处理的异常   System.InvalidOperationException:实体类型的实例   &#39;#ArtifactExecution.ExecutionStatus ArtifactExecutionStatus&#39;不可能是   跟踪,因为另一个具有键值的实例   &#39; ArtifactExecutionId:e1330424-a41f-4332-9d98-1c432d3367f8&#39;已经   被跟踪。附加现有实体时,请确保只有一个实体   附加了具有给定键值的实体实例。

更新时,我使用了ef-core的原生DbSet.Update(entity),因此,所有级联应该正常工作。

我该如何解决?

0 个答案:

没有答案