Entity Framework Core Self reference optional property

c# entity-framework-core

Question

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();
});
1
2
10/10/2016 8:08:30 AM

Accepted Answer

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.

3
10/10/2016 11:52:47 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow