我正在尝试使用实体框架代码第一种方法创建1-n关系。以下是我的课程
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; }
}
以下是我的第二堂课
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; }
}
用户和投票和1-n关系,在我的情况下,我的意思是UserID应该是投票表中的外键。但是当我用以下命令创建db时
enable-migrations -ContextTypeName ProfileOne.PO -Force
Add-migration PO
update-database
我没有得到任何外键OR列名UserID
任何帮助将不胜感激,为什么我无法取得成果。
答案 0 :(得分:1)
尝试使用以下方法:
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; }
}
有关详细信息,请查看Entity Relationships。希望这会有所帮助...
答案 1 :(得分:-1)
修改您的课程如下:
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; }
public virtual Vote Vote { get; set; }
}
public class Vote
{
[Required]
[Key]
public int VoteID { get; set; }
[Required]
public int VoteCount { get; set; }
[Required]
public int UserID { get; set; }
//[ForeignKey("UserID")]
//[Required]
public virtual User User { get; set; }
}
2个实体之间的关系由虚拟属性定义,您对它们进行了评论。