This is how my data model for USER looks like
public class User
{
/// <summary>
/// .cstor
/// </summary>
public User()
{
this.UserDetails = new UserDetails();
}
/// <summary>
/// Gets or sets the Primary key.Identity key
/// </summary>
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[ForeignKey("UserDetails")]
public int UserId { get; set; }
[Required]
[StringLength(150, MinimumLength = 1)]
public string Name { get; set; }
/// <summary>
/// Gets or sets the user details
/// </summary>
[Required]
public virtual UserDetails UserDetails { get; set; }
}
public class UserDetails
{
[Required]
public int UserDetailsId { get; set; }
[Required]
public virtual User User { get; set; }
[StringLength(1000)]
public string Address { get; set; }
[Required]
[StringLength(20, MinimumLength = 8)]
public string PhoneNumber { get; set; }
[StringLength(255, MinimumLength = 3)]
public string Email { get; set; }
[StringLength(255)]
public string Photo { get; set; }
}
I have a Create view (razor engine) where properties of User and UserDetails are filled.
But I am unable to create this because my modelstate is invalid when I save, because Userdetails.User is null. As per my understanding, this property is just to let EF know the relationship.
Can somebody show me a neat way of doing a end to end (razor to DBcontext save) saving of these related entities?
Here you have a 1-to-1 relationship.
One way to do this, if it make sense in your application, is to make
UserDetailsaComplexTypeand remove it’sUserproperty.One side effect of this is that all of the data will be stored in a single table.