Question

I have some problems with Code First and Code Migrations.

I have a User class and a UserData class (with optional information like first/last name), but when I try to run the 'Add-Migration' or 'Update-Database' command, I get several errors.

I have created the User class:

public class User
{
    public int ID { get; set; }
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
    public DateTime DateOfBirth { get; set; }

    public UserData UserData { get; set; }
    public int UserDataID { get; set; }
}

and the UserData class:

public class UserData
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

With this setup I get the error:

Multiple identity columns specified for table 'Users'. Only one identity column per table is allowed.

when trying to run 'Update-Database' (the 'Add-Migration' command runs fine).

I already tried to add public User User { get; set; } and public int UserID { get; set; } to UserData.cs, but then I get an error with the 'Add-Migration' command:

Unable to determine the principal end of an association between the types 'UserData' and 'User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations

Any idea how to fix this?

Thanks in advance.

Was it helpful?

Solution

Remove UserDataID from User class, there is no need for it. Also, make public virtual UserData UserData { get; set; } so that EF would populate it for you when you access FirstName, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top