Code First与现有数据库

时间:2011-09-28 14:46:40

标签: entity-framework-4.1

我在数据库中有一个指向自身的表,即parent_id>>类别ID。这是ER图 ER Diagram

我已将此表格建模如下,但它提供了 *错误:'类别':成员名称不能与其封闭类型相同

public class Category
{
    [Key]
    public int category_id { get; set; }
    public string category_name { get; set; }
    public int category_parent { get; set; }
    public string category_desc { get; set; }

    public virtual Category Category { get; set; }
}

我应该如何建模这样的表格?

3 个答案:

答案 0 :(得分:2)

您必须使category_parent为空,并将导航属性Category配置为标量属性category_parent。尝试使用正确的命名约定。

public class Category
{
    [Key]
    [Column("category_id")]
    public int Id { get; set; }

    [Column("category_name")]
    public string Name { get; set; }

    [Column("category_parent")]
    public int? ParentId { get; set; }

    [Column("category_desc")]
    public string Description { get; set; }

    [ForeignKey("ParentId")]
    public virtual Category ParentCategory { get; set; }
}

答案 1 :(得分:1)

我认为您只需将Category属性名称更改为其他名称,因此它与类名称不同...

public virtual Category SubCategory { get; set; }

答案 2 :(得分:1)

public class Category
{
    [Key]
    public int category_id { get; set; }
    public string category_name { get; set; }
    public int category_parent { get; set; }
    public string category_desc { get; set; }

    public int parent_category_id { get; set; } <-- ADD & setup as foreign key
    public virtual Category ParentCategory { get; set; } <-- Change name

    public virtual ICollection<Category> Categories { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Category>.HasMany(cat => cat.Categories)
            .WithRequired()
            .HasForeignKey(cat => cat.parent_category_id);        
}