//...">

EF Code First Fluent Mapping: 0-1 for many: HasOptional (), same table

I have a "Category" as shown below:

public class Category { //<Summary> //Fields... //</Summary> public Guid CategoryId { get; set; } public string CategoryName { get; set; } public bool IsDelete { get; set; } // Fields for relationships public Guid MainCategoryId { get; set; } public Category MainCategory { get; set; } public virtual ICollection<Category> ChildCategories { get; set; } } 

As you can see above, I want to create 0-one-to-many relationships in one table. I used the Fluent API for this as follows:

  HasRequired(category => category.MainCategory) .WithMany(category => category.ChildCategories) .HasForeignKey(category => category.MainCategoryId); 

But it is one-to-many, not 0-1-to-many. I am using HasOptional, but it gives me an error.

How can I do this using the Fluent API?

thanks for the answer

+4
source share
1 answer

Set the MainCategoryId property MainCategoryId zero:

 public Guid? MainCategoryId { get; set; } 

And then you can use the HasOptional method:

 HasOptional(category => category.MainCategory) .WithMany(category => category.ChildCategories) .HasForeignKey(category => category.MainCategoryId); 
+6
source

All Articles