Search code examples
c#asp.net-mvcentity-frameworkef-code-first

Create entity model Many-To-Many CodeFirst Ef6


I'd like Db use Code-First enter image description here

What I did:

    public class Responses
    {
        public int UserId { get; set; }
        public virtual AppUser AppUser { get; set; }

        public int QuestionId { get; set; } 
        public virtual Question Question { get; set; }

        public string Answer { get; set; }

    }
       
    public class Question
    {
        public int idQuestion { get; set; }
        public string TextQuestion { get; set; }
        public ICollection<Responses> Responses  { get; set; }
    }

    public class AppUser : IdentityUser<int, AppUserLogin, AppUserRole, IdentityUserClaimBase>, ICRMRepository, IEditableEntity, IEntityBase
    {
        public int idUser {get;set;}
        public ICollection<Responses> Responses { get; set; }

    }

next to I go to DbContext:

modelBuilder.Entity<Responses>()
                .HasKey(x => new {x.UserId, x.QuestionId});

            modelBuilder.Entity<Responses>()
                .HasOne(x=>x.User)

Cannot resolve symbol "HasOne"

what should I do if I would like get db like this?

How do I configure my association with fluent API? Or is there a better way to create the association table?

UPD enter image description here


Solution

  • I could solve it:

    public class AppUser : IdentityUser<int, AppUserLogin, AppUserRole, IdentityUserClaimBase>, ICRMRepository, IEditableEntity, IEntityBase
    {
        public ICollection<Response> Responses { get; set; } 
    }
    
    public class Question
    {
        public int Id { get; set; }
        public string TextQuestion { get; set; }
        public ICollection<Response> Responses  { get; set; }
    }
    
    public class Response
    {
        public int Id { get; set; }
        ***public int AppUserId { get; set; }***
        public int QuestionId { get; set; }
        
        public virtual AppUser AppUser { get; set; }
        public virtual Question Question { get; set; }
    
        public string Answer { get; set; }
    }
    

    db context:

    public DbSet<Question> Questions { get; set; }
    public DbSet<Response> Responses { get; set; }
    

    EF6 understand what I wanted