Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One to zero-or-one relationship: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is OFF

I have two entities:

public class Subscription
{
    public int SubscriptionId { get; set; }

    public virtual ICollection<SubscriptionError> SubscriptionErrors { get; set; }
}

public class SubscriptionError
{
    public int SubscriptionErrorId { get; set; }
    public int SubscriptionId { get; set; }

    public virtual Subscription Subscription { get; set; }
}

Originally, I defined the relationship between them as one-to-many in the SubscriptionErrorMap as follows:

this.HasRequired(t => t.Subscription)
            .WithMany(t => t.SubscriptionErrors)
            .HasForeignKey(d => d.SubscriptionId)
            .WillCascadeOnDelete(false);

I am using the following code for saving SubscriptionError:

context.SubscriptionErrors.Add(subscriptionError);

where subscriptionError is the entity and I am not explicitly setting the primary key field.

This used to work fine. But, when I changed this relationship to one to zero-or-one, it started to throw the following exception on saving:

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

The new mapping is:

this.HasRequired(t => t.Subscription)
            .WithOptional(t => t.SubscriptionError)
            .WillCascadeOnDelete(false);

Is there something wrong with the mapping?

like image 549
Nimish David Mathew Avatar asked Nov 06 '22 22:11

Nimish David Mathew


1 Answers

This is what worked for me:

Remove the PK field SubscriptionErrorId and set SubscriptionId as both PK and FK for SubscriptionError.

Entities would now look like the following:

public class Subscription
{
     public int SubscriptionId { get; set; }

     public virtual SubscriptionError SubscriptionError { get; set; }
}

public class SubscriptionError
{
    [ForeignKey("Subscription")]
    public int SubscriptionId { get; set; }

    [Required]
    public virtual Subscription Subscription { get; set; }
}
like image 161
Nimish David Mathew Avatar answered Nov 15 '22 14:11

Nimish David Mathew