Code first approach not creating foreign key

.net asp.net-mvc entity-framework entity-framework-6

Question

I am trying to create 1-n relationship using entity framework code first approach. Following are my classes

public class User
{

    [Key]
    public int UserID { get; set; }


    //public virtual Vote Vote { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Bio { get; set; }
    [Required]
    public string Education { get; set; }
    [Required]
    public string Experience { get; set; }

    public string Password { get; set; }

}

and following is my second class

public class Vote
{
    [Required]
    [Key]
    public int VoteID { get; set; }

    [ForeignKey("UserID")]
    [Required]
    public virtual User User { get; set; }

    //public virtual int UserID { get; set; }

    [Required]
    public int VoteCount { get; set; }
    [Required]

    public  int UserID { get; set; }


}

the user and vote and 1-n relationship, in my case what I mean is that UserID should be foreign key in Vote table. But when I done creating db with following commands

   enable-migrations -ContextTypeName ProfileOne.PO -Force

   Add-migration PO

   update-database

I am not getting any foreign key OR column name UserID

Any help will be appreciated why I am not able to achieve the result.

1
0
10/24/2016 8:10:39 AM

Accepted Answer

Try to use the following approach:

public class User
{
    [Key]
    public int UserID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Bio { get; set; }

    [Required]
    public string Education { get; set; }

    [Required]
    public string Experience { get; set; }

    public string Password { get; set; }        


    //Navigation properties
    public virtual ICollection<Vote> Votes { get; set; }
}


public class Vote
{
    [Key]
    public int VoteID { get; set; } 

    [Required]
    public int VoteCount { get; set; }  


    //Foreign key for User
    [Required]
    public int UserID { get; set; } 

    //Navigation properties
    public virtual User User { get; set; }
}


For more information, have a look at Entity Relationships. Hope this helps...

1
10/24/2016 7:27:41 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow