I have the following entity:
public class Level
{
public int LevelId { get; set; }
public int? ParentLevelId { get
Something's messed up in your migration. No repro when initializing that model:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace EfCoreTest
{
public class Level
{
public int LevelId { get; set; }
public int? ParentLevelId { get; set; }
public string Name { get; set; }
public virtual Level Parent { get; set; }
public virtual HashSet Children { get; set; }
}
public class Db : DbContext
{
public DbSet levels { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.;database=EfCoreTest;Integrated Security=true");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity()
.HasOne(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentLevelId);
}
}
class Program
{
static void Main(string[] args)
{
using (var db = new Db())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
Console.ReadKey();
}
}
}
}
creates table:
CREATE TABLE [levels] (
[LevelId] int NOT NULL IDENTITY,
[ParentLevelId] int NULL,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_levels] PRIMARY KEY ([LevelId]),
CONSTRAINT [FK_levels_levels_ParentLevelId] FOREIGN KEY ([ParentLevelId]) REFERENCES [levels] ([LevelId]) ON DELETE NO ACTION
);
Added a Migration,
PM> Add-Migration InitialCreate
and still no repro:
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EfCoreTest.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "levels",
columns: table => new
{
LevelId = table.Column(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ParentLevelId = table.Column(nullable: true),
Name = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_levels", x => x.LevelId);
table.ForeignKey(
name: "FK_levels_levels_ParentLevelId",
column: x => x.ParentLevelId,
principalTable: "levels",
principalColumn: "LevelId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_levels_ParentLevelId",
table: "levels",
column: "ParentLevelId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "levels");
}
}
}