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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With