如何在代码优先ef.1中声明一对一关系

时间:2011-10-09 13:46:28

标签: ef-code-first entity-relationship

我有两个班级

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有一个Avatar或零。

当我添加2个用户

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();

每个Avatar的0都为UserId,当然用户的1和2为Id.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

实体框架不支持一对一关系,除非它是共享主键映射。因此,在您的情况下,您不能在Avatar类中拥有导航属性User。相反,您可以在User类中拥有Avatar属性。

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; }
}

然后您可以按如下方式添加实体

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();