是否有办法从Model中设置许多表的关系

本文关键字:设置 许多表 关系 Model 是否 | 更新日期: 2023-09-27 17:54:08

我想设置一些表的关系,使表中的一些列可以为空。

[Table("tbl_useraccount")]
public class AccountViewModels
{
   [Key]
   public string AccountId { get; set; }
   public string Email { get; set; }
   public string HashPassword { get; set; }
}

,这是我想建立关系的表:

[Table("tbl_userprofile")]
public class UserProfileViewModels
{
   [Key]
   public int Id { get; set; }
   public string AccountId { get; set; }
   public string Address { get; set; }
   public int PhoneNumber { get; set; }
}

我的问题是:如何设置AccountId(在表tbl_useraccount中)是主键,并作为表tbl_userprofile中的外键?

我的子问题是:是否有必要为每个列名设置NULLNOT NULL ?如果有必要,我该怎么做?

p/s:我使用MVC 5和SQL Server.

是否有办法从Model中设置许多表的关系

我的第一个评论是,您不使用视图模型为您的数据库生成。ViewModels只用于你的视图。

要创建一个关系,您应该将AccountModel添加到UserProfile中,我添加了virtual以启用延迟加载。还要将ForeignKey数据注释添加到您希望将键映射到的额外属性(可选)

[Table("tbl_useraccount")]
public class AccountModel
{
   [Key]
   public string AccountId { get; set; }
   public string Email { get; set; }
   public string HashPassword { get; set; }
}

[Table("tbl_userprofile")]
public class UserProfileModels
{
   [Key]
   public int Id { get; set; }
   public string AccountId { get; set; }
   public string Address { get; set; }
   [ForeignKey("AccountModel")]
   public int PhoneNumber { get; set; }
   public virtual AccountModel AccountModel { get; set;}
}

如果您希望一个字段不为空,如果这是可能的。使用[Required]数据注释。"Public int PhoneNumber"不能为空,你必须这样写:"Public int?PhoneNumber"。