Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core Self reference optional property

I am using Microsoft.EntityFrameworkCore.Sqlite v1.0.1. This is my entity:

public class Category
{
    public int CategoryId { get;set;}
    public Category ParentCategory { get; set; }
    public int? ParentCategoryId { get; set; }
    public string Name { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
}

So i need to configure ParentCategory as an optional property. How can i do this in EF core? This is my fluent mapping until now:

modelBuilder.Entity<Category>(e =>
{
    e.HasKey(c => c.CategoryId);

    e.Property(c => c.DateCreated).ValueGeneratedOnAdd();
    e.Property(c => c.DateModified).ValueGeneratedOnAddOrUpdate();
});
like image 524
Daniel Avatar asked Aug 09 '26 06:08

Daniel


1 Answers

Your ParentCategoryId is already optional based on the fact that it is nullable. If it wasn't nullable, it would be required. You don't need to configure it further.

Note, you don't need to configure CategoryId as the Key for Category. It will be configured as the key because it already follows the naming convention for an entity key.

like image 166
Mike Brind Avatar answered Aug 11 '26 18:08

Mike Brind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!