我有两个班级
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.
我该如何解决这个问题?
答案 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();