InvalidOperationException due to circular dependency in Entity Framework Core

c# entity-framework entity-framework-core sql


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);
        .WithOne(s => s.License)
        .HasForeignKey<DeviceLicenseSubscriptionPlan>(s => s.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");


I am using EF Core 2.0. I probably do something wrong within the ModelBuilder? Any hints?

8/31/2017 5:17:37 PM

Accepted Answer

The problem is this line


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)
8/31/2017 6:19:45 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow