1110
1110

Reputation: 6829

Can't get one to one related objects

I have entities:

public class User
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        ...
        public virtual Profile Profile { get; set; }
        ...
public class Profile
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

When I try to get User I get error:

System.Data.Edm.EdmEntityType: : EntityType 'Profile' has no key defined. Define the key for this EntityType.

When I change entities to:

public class User
    {
        [Key]
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        ...
        public virtual Profile Profile { get; set; }
        ...
public class Profile
    {
        [Key]
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

I get error:

{"Invalid column name 'Profile_UserId'."}

What am I doing wrong?
enter image description here

Upvotes: 0

Views: 71

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

According to http://blog.bennymichielsen.be/2011/06/02/entity-framework-4-1-one-to-one-mapping/ it could work:

public class User
{
        [Key]
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public virtual Profile Profile { get; set; }
}

public class Profile
{
        [Key]
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required]
        public virtual User User { get; set;}
}

Upvotes: 1

Related Questions