Reputation: 59031
I am getting the following InvalidOperationException when I try to save an entity with a one-to-one relationship:
System.InvalidOperationException: Unable to save changes because a circular dependency was detected in the data to be saved: 'ForeignKey: DeviceLicenseSubscriptionPlan {'LicenseId'} -> DeviceLicense {'Id'} Unique ToPrincipal: License, ForeignKey: DeviceLicense {'SubscriptionPlanId'} -> DeviceLicenseSubscriptionPlan {'Id'} ToPrincipal: SubscriptionPlan'.
Here is my modell:
public class DeviceLicense
{
public Guid? Id { get; set; }
public int DeviceLimit { get; set; }
public DeviceLicenseSubscriptionPlan SubscriptionPlan { get; set; } = new DeviceLicenseSubscriptionPlan();
}
public class DeviceLicenseSubscriptionPlan
{
public Guid? Id { get; set; }
public Guid? LicenseId { get; set; }
public DeviceLicense License { get; set; }
}
Here the OnModelCreating()
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var deviceLicense = modelBuilder.Entity<DeviceLicense>().ToTable("DeviceLicense");
deviceLicense.HasKey(l => l.Id);
deviceLicense.HasOne<DeviceLicenseSubscriptionPlan>()
.WithOne(s => s.License)
.HasForeignKey<DeviceLicenseSubscriptionPlan>(s => s.LicenseId)
.HasConstraintName("LicenseId");
deviceLicense.Property(l => l.DeviceLimit).HasColumnName("DeviceLimit");
var deviceLicenseSubPlan = modelBuilder.Entity<DeviceLicenseSubscriptionPlan>().ToTable("DeviceLicenseSubscriptionPlan");
deviceLicenseSubPlan.HasKey(s => s.Id);
deviceLicenseSubPlan.Property(s => s.Id).HasColumnName("SubscriptionPlanId");
base.OnModelCreating(modelBuilder);
}
I am using EF Core 2.0. I probably do something wrong within the ModelBuilder? Any hints?
Upvotes: 1
Views: 2120
Reputation: 205939
The problem is this line
deviceLicense.HasOne<DeviceLicenseSubscriptionPlan>()
It basically tells EF that there is no navigation property to DeviceLicenseSubscriptionPlan
in DeviceLicense
. However there is a navigation property, so EF by convention maps it to a second relationship with FK in DeviceLicense
pointing to DeviceLicenseSubscriptionPlan
. Which of course with the combination of the desired FK in DeviceLicenseSubscriptionPlan
creates a cycle.
Make sure fluent configuration uses the correct overloads which exactly represent the presence/absence of a navigation property in either side of the relationship. In this particular case, replace the above with
deviceLicense.HasOne(l => l.SubscriptionPlan)
Upvotes: 5