Entity Framework skipping Identity column Concurre

2019-08-20 18:42发布

问题:

I am working with Entity Framework 5 code-first and I have a situation where I have an entity which has an Identity column that is not part of the primary key. When I add a new record and invoke SaveChanges on the context, I get a ConcurrencyException. If I change the primary key on the entity map to SCHED_ID or remove SCHED_ID from the entity map altogether, SaveChanges completes without issue. I suspect that since SCHED_ID is defined as an int, it defaults to a value of zero and Entity Framework thinks it has changed when the database actually assigns it a value (thus causing a ConcurrencyException). Am I correct in my assumption? How can I work around this without changing the key on the entity map to SCHED_ID?

The entity is defined as follows:

public partial class Sched
{
    public int SCHED_ID { get; set; }
    public System.DateTime DATE_QUEUED { get; set; }
    public string STATUS_CODE { get; set; }
}

public class SchedMap : EntityTypeConfiguration<Sched>
{
    public SchedMap()
    {
        // Primary Key
        this.HasKey(t => new { t.STATUS_CODE, t.DATE_QUEUED });

        //Properties
        this.Property(t => t.SCHED_ID)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .IsConcurrencyToken(false);

        // Table & Column Mappings
        this.ToTable("Sched");
        this.Property(t => t.SCHED_ID).HasColumnName("SCHED_ID");
        this.Property(t => t.STATUS_CODE).HasColumnName("STATUS_CODE");
        this.Property(t => t.DATE_QUEUED).HasColumnName("DATE_QUEUED");
    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new SchedMap());
}