【问题标题】:EF Code First Fluent Mapping: 0-1 to Many: HasOptional(), same tableEF Code First Fluent Mapping: 0-1 to Many: HasOptional(),同一张表
【发布时间】:2013-09-21 05:47:51
【问题描述】:

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

 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 对多的关系。我为此使用了 Fluent API,如下所示:

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

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

如何使用 Fluent API 做到这一点?

感谢回复

【问题讨论】:

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


    【解决方案1】:

    使MainCategoryId 属性可以为空:

    public Guid? MainCategoryId { get; set; }
    

    然后你可以使用HasOptional方法:

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

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多