0

I needed a 1:1 mapping of DivisionParticipant and Team with both IDs being auto increment. I did this because we wanted to use to Nullable FK's, Team and Player. Before Team ID was the PK to DivisionParticipant ID, but now DivisionParticipant ID is auto increment and Team is now added as a property with the FK to get the 1:1 working. This works fine and minimal code changes were needed when we do a read, but now on a save we get this error below. The ID of DivisionParticipant was made to autoincrement so I am unsure what column it is speaking of?

Cannot insert explicit value for identity column in table 'DivisionParticipant' when IDENTITY_INSERT is set to OFF

Classes

public class DivisionParticipant
{
    public int Id {get; set;}
    public virtual Team Team { get; set; }
    public virtual Player Player { get; set; }
}

 public class Team 
{
    public int Id {get; set;}
    public virtual DivisionParticipant DivisionParticipant { get; set; }
}

DataContext

        modelBuilder.Entity<Team>()
        .HasOptional(t => t.DivisionParticipant)
        .WithRequired(t => t.Team);
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • 1
    First of all: **Who** is speaking. Your app or SQL Server? It sounds like SQL Server, but I can't see any SQL in your code. There must be some INSERT statement that causes this "speaking". – Wolfgang Kais Oct 13 '18 at 20:44
  • Pretty sure that its an obvious EF error but it is coming from VS. Team is assigned to DivisionParticipant while DivisionParticipant is putting added to the DataContext. That is pretty much all I know. – Mike Flynn Oct 13 '18 at 20:45
  • Possible duplicate of [Mapping foreign key in HasOptional().WithOptionalDependent() relation in Entity Framework 6](https://stackoverflow.com/questions/32313842/mapping-foreign-key-in-hasoptional-withoptionaldependent-relation-in-entity) – Mike Flynn Oct 14 '18 at 12:03

1 Answers1

0

EF6 doesn't support 1:1 relationships without the FK on the dependent side being the PK which means the PK on one side cannot use an identity. Check out this answer for the explanation from the EF Program Manager.

Moho
  • 15,457
  • 1
  • 30
  • 31