Is there anyway to set the relationship of many tables from Model?

59 views Asked by At

I want to set the relationship of some tables and make some columns in the table can be null.

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

and here is the table which I want to make relationship:

[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; }
}

My question is: How to set AccountId (in the table tbl_useraccount) is the primary key and as the foreign key in the table tbl_userprofile from Model?

And my sub-question is: Is it necessary to set NULL or NOT NULL for per column name? If it is necessary, how can I do that?

p/s: I'm using MVC 5 and SQL Server.

1

There are 1 answers

0
Jelle Oosterbosch On

First remark I have is that you don't use viewmodels for your database generation. ViewModels are only used for your views.

To create a relationship, you should add the AccountModel to the UserProfile, I added virtual to enable lazy loading. Also add the ForeignKey data annotation to the extra property you want to map your key to (optional)

[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;}
}

If you want a field not to be null, if this is even possible. Use the [Required] data annotation. "Public int PhoneNumber" can not be null, you'll have to write it as following: "Public int? PhoneNumber".