I have an issue in regards to creating a database from code first in entity framework. I have the following three classes 1 Person, 2 PersonAddress, 3 PersonEmploymentHistory as shown below.
namespace DataAccess.Models
{
[Table("Profile")]
public class Person
{
[Key]
public int UserId { get; set; }
[Required(ErrorMessage = "Firstname is required")]
public string PersonFirstName { get; set; }
[Required(ErrorMessage = "Surname is required")]
public string PersonSurname { get; set; }
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
public string PersonEmail { get; set; }
public int Age { get; set; }
[Required(ErrorMessage = "Contact Number required")]
public Int64 PersonNumber { get; set; }
public bool IsActive { get; set; }
[ForeignKey("AddressDetails")]
public int AddressId { get; set; }
public virtual PersonAddress AddressDetails { get; set; }
[ForeignKey("EmploymentHistory")]
public int EmployerId { get; set; }
public virtual PersonEmploymentHistory EmploymentHistory { get; set; }
}
}
PersonAddress Class
namespace DataAccess.Models
{
[Table("AddressDetails")]
public class PersonAddress
{
[Key]
public int AddressId { get; set; }
[ForeignKey("UserId")]
public int UserId { get; set; }
[Required(ErrorMessage = "Address Line 1 required")]
public string AddressLine1 { get; set; }
[Required(ErrorMessage = "Address Line 2 required")]
public string AddressLine2 { get; set; }
[Required(ErrorMessage = "Postcode required")]
[DataType(DataType.PostalCode)]
public string PostCode { get; set; }
}
}
PersonEmploymentHistory
namespace DataAccess.Models
{
[Table("EmploymentHistory")]
public class PersonEmploymentHistory
{
[Key]
public int EmployerId { get; set; }
public string EmployerName { get; set; }
public decimal EmployeeSalary { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string ReasonForLeaving { get; set; }
[ForeignKey("UserId")]
public int UserId { get; set; }
}
}
And this is my Context class
public class Context : DbContext
{
public Context()
: base("DefaultConnection")
{
Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<Context>());
}
public DbSet<Person> Person { get; set; }
public DbSet<PersonAddress> PersonAddress { get; set; }
public DbSet<PersonEmploymentHistory> PersonEmployment { get; set; }
}
Now I have followed tutorials when creating foreign keys etc but when I run my project and try to insert data into the person table I get the following error
The property 'UserId' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.