umki
umki

Reputation: 779

Asp.Net MVC Codefirst Model Relation to the Same Model

I have a model and i want to put an extra field which can be populated form the same model. IE: Categories and and sub-categories.

In my example, visitor can add an filetype but if file type is under an another file type, he can choose, But i cant work it out. Below you can see my model.

 public class HrFileType
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Dosya Adı")]
        public int Name { get; set; }

        public int? HrFileTypeId { get; set; }
        public virtual HrFileType HrFileType2 { get; set; }
    }

Upvotes: 0

Views: 81

Answers (2)

Lin
Lin

Reputation: 15188

You just need to add a ForeignKeyAttribute like below:

public class HrFileType
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Dosya Adı")]
    public int Name { get; set; }

    public int? HrFileTypeId { get; set; }

    [ForeignKey("HrFileTypeId")]
    public virtual HrFileType HrFileType2 { get; set; }
}

You can also use fluent API to achieve this:

public class HrFileType
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Dosya Adı")]
    public int Name { get; set; }

    public int? HrFileTypeId { get; set; }
    public virtual HrFileType HrFileType2 { get; set; }
}

public class YourDbContext : DbContext
{
    public DbSet<HrFileType> HrFileTypes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //
        modelBuilder.Entity<HrFileType>()
                    .HasOptional(c => c.HrFileType2)
                    .WithMany()
                    .HasForeignKey(c => c.HrFileTypeId);
    }
}

Upvotes: 1

Heberda
Heberda

Reputation: 820

Have you tried listing the other file types?

 public class HrFileType
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Dosya Adı")]
        public int Name { get; set; }

        public List<HrFileType> RelatedTypes { get; set; }
    }

then using Entity Frameworks fluent API in the DbContext, try explicitly declaring a many to many map.

modelbuilder.Entity<HrFileType>().HasMany(x => x.RelatedTypes).WithMany();

I'd be very interested to see if this works. It's the only logical solution I can think of without having some kind of parent class.

Upvotes: 0

Related Questions