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.
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...