I have a table in database which points to itse开发者_如何学编程lf, i.e. parent_id >> category id. This is the ER diagram
I have modelled this table like following, but it gives *Error : 'Category': member names cannot be the same as their enclosing type :
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; }
}
How should I model such tables ?
You have to make category_parent
nullable and configure navigational property Category
to the scalar property category_parent
. Try to use proper naming convensions.
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; }
}
I think you just need to change the Category property name to something else, so it is not the same as the class name...
public virtual Category SubCategory { get; set; }
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);
}
精彩评论