Search code examples
c#asp.netasp.net-coreentity-framework-coreef-code-first

How to get the foreign key column that auto created by ef core?


Hello I want to implement a one to many relationship with only one entity with itself, but I want to access the foreign key that auto generated by Ef, unfortunately, I tested many ways such as using fluent api and give a parentId as foreign key e.g, but all of them got errors, these are my classes:

public class EntityBase
    {
        public int Id { get; set; }
        public DateTime CreationDate { get; set; } = DateTime.Now;
    }
 public class Category : EntityBase
    {
        public string Title { get; set; } = string.Empty;
        public bool ShowInMenu { get; set; }
public List<Category> ChildCategories { get; set; } = new List<Category>();
}

when I run the command Add-Migration, the migration produces this class for me :

migrationBuilder.AddColumn<int>(
                name: "CategoryId",
                table: "ProductCategories",
                type: "int",
                nullable: true);

            migrationBuilder.CreateIndex(
                name: "IX_ProductCategories_CategoryId",
                table: "ProductCategories",
                column: "CategoryId");

            migrationBuilder.AddForeignKey(
                name: "FK_ProductCategories_ProductCategories_CategoryId",
                table: "ProductCategories",
                column: "CategoryId",
                principalTable: "ProductCategories",
                principalColumn: "Id");

And I want to access the data of the column CategoryId auto generated by ef from my code, but I don't know how can I do this? could anyone please help me? thanks a lot.


Solution

  • You could check the doc related with shadow properties

    I tried as below:

    In dbcontext:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>().Property<int?>("CategoryId").IsRequired(false);
            modelBuilder.Entity<Category>().HasMany(x=>x.ChildCategories).WithOne().HasForeignKey("CategoryId").IsRequired(false).OnDelete(DeleteBehavior.NoAction);
        }
    

    Access target Fk:

    var targetfk = _context.Entry<Category>(targetitem).Property("CategoryId").CurrentValue;
    

    Worked as expected:

    enter image description here

    enter image description here