Search code examples
c#.netasp.net-core-mvcef-code-first

Ef core Creating additional column for a navigation property with Name *ID1


I'm using Ef core Code First to generate a Database. But I'm not sure why it's creating a new column with *ID1.

Entity

public class Room : BaseEntity
{
    public string Name { get; set; }
    public string UniqueCode { get; set; }
    public int BranchId { get; set; }
    public virtual Branch Branch { get; set; }
    public CommonStatus Status { get; set; }
}

Configuration

public class RoomConfiguration : IEntityTypeConfiguration<Room>
{
    public void Configure(EntityTypeBuilder<Room> builder)
    {
        builder.Property(t => t.Name).IsRequired().HasMaxLength(10);
        builder.Property(t => t.UniqueCode).IsRequired().HasMaxLength(10);
        builder.HasIndex(p => p.Status);
        builder.HasOne(s => s.Branch)
            .WithMany()
            .HasForeignKey(e => e.BranchId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

Migration

migrationBuilder.CreateTable(
                name: "Room",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(maxLength: 10, nullable: false),
                    UniqueCode = table.Column<string>(maxLength: 10, nullable: false),
                    BranchId = table.Column<int>(nullable: false),
                    Status = table.Column<int>(nullable: false),
                    BranchId1 = table.Column<int>(nullable: true)
                }

As You can sett the migration script actually has BranchId1 which I never defined. and this happening in some entity as well but not all. I just want to know why it's happening thanks


Solution

  • You have not specified the navigation property on .WithMany().

    WithMany():

    Configures this as a one-to-many relationship. Note that calling this method with no parameters will explicitly configure this side of the relationship to use no navigation property, even if such a property exists on the entity type. If the navigation property is to be used, then it must be specified.

    What happens is EF first configures your relation that you made with the fluent API, then it also creates a relation for List<Rooms>. Since BranchId is already used for your fluent relationship it creates a second FK called BranchId1.

    So your relation should be:

    modelBuilder.Entity<Room>().HasOne(s => s.Branch)
        .WithMany(x => x.Rooms)
        .HasForeignKey(e => e.BranchId)
        .OnDelete(DeleteBehavior.Restrict);