Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The property '' on entity type '' has a temporary value while attempting to change the entity's state to 'Modified' #22027

Closed
cxc256 opened this issue Aug 12, 2020 · 4 comments · Fixed by #22221
Labels
area-save-changes closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported type-bug
Milestone

Comments

@cxc256
Copy link

cxc256 commented Aug 12, 2020

I have a one to many relationship. I believe I have it set up correctly, please see the code below. A Batch will contain a bunch of Accounts. Everything works correctly when all objects are new and inserted into the database at once. However, there is a user case where Accounts are saved first, before being associated with a Batch. Then later, a Batch is created the existing batchless accounts are added to the Batch. When I try to save, I get the following error: The property 'BatchId' on entity type 'Account' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

I am using ASP.Net Core 3.1 with EF Core 3.1.6 for SQLServer. I'm using Visual Studio 2019 16.6 on Windows 10/2016

public class Batch
{
    private List<Account> _accounts;
    
    public int BatchId { get; set; }
    public int AccountCount { get; internal set; }
    public decimal AccountTotal { get; internal set; }
    public virtual IReadOnlyCollection<Account> Accounts => _accounts?.AsReadOnly( );
    
    public void AddAccount(Account account)
    {
        if( account == null )
            return;

        if( _accounts == null )
            _accounts = new List<Account>( );

        _accounts.Add( account );
        AccountCount++;
        AccountTotal += account.OriginalBalance;
    }
}

public class Account
{
    public int AccountId { get; set; }
    public decimal OriginalBalance { get; set; }
}

public class BatchConfig : IEntityTypeConfiguration<Batch>
{
    public void Configure( EntityTypeBuilder<Batch> builder )
    {
        if( builder == null )
            throw new ArgumentNullException( nameof( builder ) );

        builder.ToTable( "XXXXX" ).HasKey( e => e.BatchId );

        builder.Property( e => e.BatchId ).UseIdentityColumn( );

        builder
            .HasMany( e => e.Accounts )
            .WithOne( )
            .HasForeignKey( e => e.BatchId )
            .HasPrincipalKey( e => e.BatchId )
            ;

    }
}

public class AccountConfig : IEntityTypeConfiguration<Account>
{
    public void Configure( EntityTypeBuilder<Account> builder )
    {
        if( builder == null )
            throw new ArgumentNullException( nameof( builder ) );

        builder.ToTable( "XXXXX" ).HasKey( e => e.AccountId );
        builder.Property( e => e.AccountId ).UseIdentityColumn( );

        builder.Property( e => e.TotalAdjustments ).HasComputedColumnSql( "TotalAdjustments" );
        builder.Property( e => e.TotalDisbursements ).HasComputedColumnSql( "TotalDisbursements" );

        builder.Property( e => e.BatchId ).HasColumnName( "DepositBatchId" );

        builder
            .HasOne( e => e.CheckPayerCompany )
            .WithOne( )
            .HasForeignKey<Account>( e => e.CheckCompanyId );       

        builder
            .HasOne( e => e.AccountType )
            .WithOne( )
            .HasForeignKey<Account>( e => e.AccountTypeId );

        builder
            .HasOne( e => e.DepositTypeLookup )
            .WithOne( )
            .HasForeignKey<ClipAccount>( e => e.DepositType );

        builder
            .HasOne( e => e.EmployeeContribPercentage )
            .WithOne( )
            .HasForeignKey<Account>( e => e.EECPercentId );

        builder
            .HasOne( e => e.EmployerPensionContribPercentage )
            .WithOne( )
            .HasForeignKey<Account>( e => e.ERPPercentId );

        builder
            .HasOne( e => e.EmployerHealthContribPercentage )
            .WithOne( )
            .HasForeignKey<Account>( e => e.ERHPercentId );
    }
}

Steps to reproduce

  1. Save an Account in the database.
  2. In another session, pull that account from database.
  3. Create new Batch
    4 .Call Batch.AddAccount(account)
  4. Save Batch to Database
@ajcvickers
Copy link
Member

@cxc256 The code snippets above do not compile and it's not clear what the missing parts should be. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

@cxc256
Copy link
Author

cxc256 commented Aug 15, 2020

@ajcvickers , attached is a sample. I used the internal custom repository pattern I'm required to use for the project.
EFCoreTest.zip

@ajcvickers
Copy link
Member

@cxc256 Thanks for the repro code.

Note for team: the issue here is in changing from an Added state to a Modified state when the entity has a temporary FK value. See simplified repro code below. We currently throw, but for an FK it is valid to have a temporary value pointing to a new Added principal.

public class SomeDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>();
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(Your.SqlServerConnectionString);
}

public static class Program
{
    public static void Main()
    {
        using (var context = new SomeDbContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var post = new Post { Id = 1 };
            context.Add(post);
            
            var blog = new Blog();
            context.Add(blog);

            // Associate with the principal
            post.Blog = blog;

            // Works if this state change is done before associating the Added principal
            // Fails if it is done after, like here.
            context.Entry(post).State = EntityState.Modified;

            context.ChangeTracker.DetectChanges();
        }
    }
}

public class Blog
{
    public int Id { get; set; }
    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    
    public int? BlogId { get; set; }
    public Blog Blog { get; set; }
}
Unhandled exception. System.InvalidOperationException: The property 'BlogId' on entity type 'Post' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry.set_State(EntityState value)
   at Program.Main() in /home/ajcvickers/AllTogetherNow/Daily/Daily.cs:line 59

@AndriySvyryd
Copy link
Member

Related: #14192

@ajcvickers ajcvickers added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label Aug 25, 2020
@ajcvickers ajcvickers modified the milestones: 5.0.0, 5.0.0-rc1 Aug 25, 2020
@ajcvickers ajcvickers modified the milestones: 5.0.0-rc1, 5.0.0 Nov 7, 2020
@ajcvickers ajcvickers removed their assignment Sep 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-save-changes closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported type-bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants