0

I have two classes

public class User
    {
        [Key]
        public int Id { get; set; }
        public Avatar Avatar { get; set; }

    }

public class Avatar
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string LinkInString { get; set; }

        [NotMapped]
        public Uri Link
        {
            get { return new Uri(LinkInString); }
            set { LinkInString = value.AbsoluteUri; }
        }

        public int UserId { get; set; }
    }

User has one Avatar or zero.

When I add 2 Users

db.Users.Add(new User() { Avatar = new Avatar() { Link = new Uri("http://myUrl/%2E%2E/%2E%2A") }});
db.Users.Add(new User() { Avatar = new Avatar() { Link = new Uri("http://myUrl/%2E%2E/%2E%2B") }});
db.SaveChanges();

every Avatar has 0 as UserId, and of course Users has 1 and 2 as its Id.

How can I fix this?

user278618
  • 19,306
  • 42
  • 126
  • 196

1 Answers1

0

Entity framework does not support one-to-one relationships unless it is a shared primary key mapping. So in your case you can not have a navigational property Avatar in the User class. Instead you can have User property in Avatar class.

public class User
{
        [Key]
        public int Id { get; set; }


}

public class Avatar
{
        [Key]
        public int Id { get; set; }

        [Required]
        public string LinkInString { get; set; }

        [NotMapped]
        public Uri Link
        {
            get { return new Uri(LinkInString); }
            set { LinkInString = value.AbsoluteUri; }
        }

        public int UserId { get; set; }

        public virtual User User { get; set; }
}

Then you can add entities as follows

var user = new User();
var avatar = = new Avatar() { User = user, Link = new Uri("http://myUrl/%2E%2E/%2E%2A") };
db.Users.Add(user);
db.SaveChanges();
Eranga
  • 32,181
  • 5
  • 97
  • 96
  • You are almost right. I can have a navigational property Avatar in the User class, but only then I haven't a navigational property User in the Avatar class. So there are 2 options. Actually there is a 3rd option - User and Avatar could exists in the same table and we could add a property Id in the Avatar class and add HasRequired(a => a.Avatar).WithRequiredPrincipal(); in the UserConfiguration, and HasKey(a => a.Id); in the AvatarConfiguration. – user278618 Oct 09 '11 at 15:36