0

I have a User entity in my DbContext. What I want is that users should be able to give references/leave comments for each other, therefore I have created Reference entity.

public class Reference
{
    public virtual User By { get; set; } // user who leaves a reference

    public virtual User To { get; set; } // user who has given a reference

    public string Opinions { get; set; }
}

in User entity

public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given

public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given

What should I do to make it work with either DataAnnonations or FluentAPI, or how would you approach to this and solve?

mnyarar
  • 515
  • 1
  • 6
  • 13
  • Make what work with DataAnnotations or FluentAPI? What is wrong with your implementation? – PeonProgrammer Sep 25 '15 at 21:15
  • i'm confused because i'm trying to use same entity 'User' for 'Reference' entity. Actually, I've added a migration and updated my database couple of minutes ago. User_Id and User_Id1 columns were generated. I'm not sure if I can use User_Id for ReferencedBy and User_Id1 for ReferencedTo as it's intended. – mnyarar Sep 25 '15 at 21:29

1 Answers1

0

You need to do something like this:

public class Reference
{
    public int ReferenceId { get; set; }

    public int ByUserId { get; set; }

    public virtual User By { get; set; } // user who leaves a reference

    public int ToUserId { get; set; }

    public virtual User To { get; set; } // user who has given a reference

    public string Opinions { get; set; }
}

public class User
{
    public int UserId { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given

    public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given
}

public class MyContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Reference> References { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Reference>()
            .HasRequired(x => x.By)
            .WithMany(x => x.ReferencedBy)
            .HasForeignKey(x => x.ByUserId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Reference>()
            .HasRequired(x => x.To)
            .WithMany(x => x.ReferencedTo)
            .HasForeignKey(x => x.ToUserId)
            .WillCascadeOnDelete(false);
    }
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62