EF Code First Fluent Mapping:0-1到Many:HasOptional(),同一个表

时间:2013-09-21 05:47:51

标签: c# entity-framework fluent-nhibernate ef-code-first one-to-many

我有一个“类别”实体如下:

 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; }
 }

如上所示,我想在同一个表中创建0-one-to-many关系。我使用Fluent API如下:

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

但它是一对多,不是0-1对多。我使用 HasOptional ,但它给我一个错误。

如何使用Fluent API执行此操作?

感谢回复

1 个答案:

答案 0 :(得分:6)

使MainCategoryId属性可以为空:

public Guid? MainCategoryId { get; set; }

然后你可以使用HasOptional方法:

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