Foreign key {'X'} on entity type {T} cannot have a required dependent end since it is not unique.
Hi,
I have had the following code working in a .NET Standard 2.0 library with EF Core 3.1.11.
Now that I have updated that library to .NET 6 (with nullable enabled) and EF Core 6.0.11 the code is failing at runtime.
I have tried completely removing the IsRequired(false). I have also tried explicitly setting it as IsRequired() but still the error occurs.
My existing code
Domain Entities
Marketplace
using Domain.Partners;
namespace Domain.Marketplaces;
public class Marketplace
{
public Guid Id { get; set; }
/// <summary>
/// Name of the entity.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Description of the entity.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Partner the marketplace belongs to.
/// </summary>
public virtual Partner Partner { get; set; }
/// <summary>
/// ID of the partner the marketplace belongs to.
/// </summary>
public int PartnerId { get; set; }
/// <summary>
/// The first category in the Marketplace hierarchy.
/// </summary>
public virtual MarketplaceCategory RootItem { get; set; }
/// <summary>
/// ID of the first item in the marketplace.
/// </summary>
public int? RootItemId { get; set; }
}
MarketplaceCategory (inherits from abstract base class MarketplaceItem)
namespace Domain.Marketplaces;
public class MarketplaceCategory : MarketplaceItem
{
/// <summary>
/// Items that make up the category.
/// </summary>
public virtual IList<MarketplaceItem> Items { get; set; }
/// <summary>
/// Indicates if the search is enabled.
/// </summary>
public bool SearchEnabled { get; set; }
}
MarketplaceItem (abstract base class)
namespace Domain.Marketplaces;
public abstract class MarketplaceItem
{
public int Id { get; set; }
/// <summary>
/// Name of the entity.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Description of the entity.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The Marketplace this item belongs to.
/// </summary>
public virtual Marketplace Marketplace { get; set; }
/// <summary>
/// ID of the marketplace this item belongs to.
/// </summary>
public Guid MarketplaceId { get; set; }
/// <summary>
/// Parent item that contains this item.
/// Only null if item is root of marketplace.
/// </summary>
public virtual MarketplaceCategory ParentItem { get; set; }
/// <summary>
/// ID of the parent item.
/// </summary>
public int? ParentItemId { get; set; }
}
Partner
namespace Domain.Partners;
public class Partner
{
public int Id { get; set; }
/// <summary>
/// Name of the entity.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Description of the entity.
/// </summary>
public string Description { get; set; }
}
Entity Type Configuration
MarketplaceMap configures the entity Marketplace
using Domain.Marketplaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Data.Mapping.Marketplaces;
class MarketplaceMap : IEntityTypeConfiguration<Marketplace>
{
public void Configure(EntityTypeBuilder<Marketplace> builder)
{
builder.ToTable("marketplace");
builder.HasKey(m => m.Id);
builder.HasOne(m => m.Partner).WithMany().IsRequired().HasForeignKey(m => m.PartnerId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne(m => m.RootItem).WithMany().IsRequired(false).HasForeignKey(m => m.RootItemId).OnDelete(DeleteBehavior.Cascade);
}
}
Error message at runtime
The error message is thrown in the Configure method of the MarketplaceMap entity configuration on the final line.
builder.HasOne(m => m.RootItem).WithMany().IsRequired(false).HasForeignKey(m => m.RootItemId).OnDelete(DeleteBehavior.Cascade);
Error message:
The foreign key {'RootItemId'} on the entity type 'Marketplace' cannot have a required dependent end since it is not unique.
Stack trace
at Microsoft.EntityFrameworkCore.Metadata.Internal.ForeignKey.SetIsRequiredDependent(Nullable`1 required, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.IsRequiredDependent(Nullable`1 required, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.ReplaceForeignKey(InternalEntityTypeBuilder principalEntityTypeBuilder, InternalEntityTypeBuilder dependentEntityTypeBuilder, Nullable`1 navigationToPrincipal, Nullable`1 navigationToDependent, IReadOnlyList`1 dependentProperties, IReadOnlyList`1 oldNameDependentProperties, IReadOnlyList`1 principalProperties, Nullable`1 isUnique, Nullable`1 isRequired, Nullable`1 isRequiredDependent, Nullable`1 isOwnership, Nullable`1 deleteBehavior, Boolean removeCurrent, Boolean oldRelationshipInverted, Nullable`1 principalEndConfigurationSource, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.ReplaceForeignKey(ConfigurationSource configurationSource, InternalEntityTypeBuilder principalEntityTypeBuilder, InternalEntityTypeBuilder dependentEntityTypeBuilder, Nullable`1 navigationToPrincipal, Nullable`1 navigationToDependent, IReadOnlyList`1 dependentProperties, IReadOnlyList`1 oldNameDependentProperties, IReadOnlyList`1 principalProperties, Nullable`1 isUnique, Nullable`1 isRequired, Nullable`1 isRequiredDependent, Nullable`1 isOwnership, Nullable`1 deleteBehavior, Boolean removeCurrent, Nullable`1 principalEndConfigurationSource, Boolean oldRelationshipInverted)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.HasForeignKey(IReadOnlyList`1 properties, EntityType dependentEntityType, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyPropertyDiscoveryConvention.DiscoverProperties(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext context)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyPropertyDiscoveryConvention.ProcessForeignKey(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext context)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyPropertyDiscoveryConvention.ProcessForeignKeyAdded(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext`1 context)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnForeignKeyPrincipalEndChanged(IConventionForeignKeyBuilder relationshipBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.HasEntityTypes(EntityType principalEntityType, EntityType dependentEntityType, Nullable`1 principalEndConfigurationSource, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalForeignKeyBuilder.HasEntityTypes(EntityType principalEntityType, EntityType dependentEntityType, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Builders.ReferenceNavigationBuilder.WithManyBuilder(MemberIdentity collection)
at Microsoft.EntityFrameworkCore.Metadata.Builders.ReferenceNavigationBuilder`2.WithMany(String navigationName)
at Cyclr.Data.Mapping.Marketplaces.MarketplaceMap.Configure(EntityTypeBuilder`1 builder) in C:\Users\{username}\source\repos\Data\Mapping\Marketplaces\MarketplaceMap.cs:line 14
at Microsoft.EntityFrameworkCore.ModelBuilder.ApplyConfiguration[TEntity](IEntityTypeConfiguration`1 configuration)
Include provider and version information
EF Core version: 6.0.11
Database provider: Pomelo.EntityFrameworkCore.MySql version 6.0.2
Target framework: .NET 6.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.4.1
N.B. I have tried to create a small repro of the issue using a new console app and the existing entities (cut down version).
For whatever reason it seems to work in the repro, ~~I'm not sure why as the code AFAIK is the same?!~~
Update 22/11/2022 13:43
I have now compared the migrations create by add-migration between the existing and the cut down entity versions in the repro app.
The FK FK_marketplace_marketplaceitem_RootItemId that was originally created was done so in the table definition as a constraint:
migrationBuilder.CreateTable(
name: "marketplace",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
PartnerId = table.Column<int>(nullable: false),
RootItemId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_marketplace", x => x.Id);
table.ForeignKey(
name: "FK_marketplace_partner_PartnerId",
column: x => x.PartnerId,
principalTable: "partner",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_marketplace_marketplaceitem_RootItemId",
column: x => x.RootItemId,
principalTable: "marketplaceitem",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
But in the repro app the same FK was created, but not in the table definition as a constraint but as an explicitly added FK:
migrationBuilder.AddForeignKey(
name: "FK_marketplace_marketplaceitem_RootItemId",
table: "marketplace",
column: "RootItemId",
principalTable: "marketplaceitem",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
Should this make any difference?
@cyclr-adrian Try making RootItem nullable:
public virtual MarketplaceCategory? RootItem { get; set; }
Likely Duplicate of #27956
I have the same issue with the following code in version 8.0.0:
public class UserEntityConfiguration : IEntityTypeConfiguration<UserEntity>
{
public void Configure(EntityTypeBuilder<UserEntity> builder)
{
builder.HasOne(user => user.CreateUser)
.WithMany()
.HasPrincipalKey(user => user.Id)
.HasForeignKey(user => user.CreateUserId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(user => user.UpdateUser)
.WithMany()
.HasPrincipalKey(user => user.Id)
.HasForeignKey(user => user.UpdateUserId)
.OnDelete(DeleteBehavior.Restrict);
// Has to be before "builder.HasOne(user => user.UpdateUser)" for some reason
builder.HasOne(user => user.DeactivateUser)
.WithMany()
.HasForeignKey(user => user.DeactivateUserId)
.HasPrincipalKey(user => user.Id)
.OnDelete(DeleteBehavior.Restrict);
}
}
public class UserEntity
{
public Guid? DeactivateUserId { get; set; }
public UserEntity? DeactivateUser { get; set; }
public Guid CreateUserId { get; set; }
public UserEntity CreateUser { get; set; }
public Guid UpdateUserId { get; set; }
public UserEntity UpdateUser { get; set; }
}
Will throw the following exception: System.InvalidOperationException: 'The foreign key {'UpdateUserId'} on the entity type 'UserEntity' cannot have a required dependent end since it is not unique.'
The only workaround is to move the code block starting with "builder.HasOne(user => user.DeactivateUser)" to the top.