asp.net MVC用户好友LazyLoad

时间:2012-06-06 21:20:14

标签: asp.net-mvc-3 lazy-loading

如果我尝试先使用代码, 用户类:

public class User
{
    [Key]
    public Guid ID { get; set; }

    [Required(ErrorMessage = "You must pick a user name")]
    [DisplayName("User Name")]
    public string Username { get; set; }

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

    [Required(ErrorMessage = "You give a valid email address")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }        
    [Required]
    public DateTime CreateAt { get; set; }

    public string Image { get; set; }

    public bool RemeberMe { get; set; }

    public bool Dummy { get; set; }

    public virtual ICollection<UserFriend> Friends { get; set; }
 } 

UserFriend类: - 保持用户之间的关系

public class UserFriend
{
    [Key, Column(Order = 0), ForeignKey("User")]
    public Guid UserId { get; set; }
    public User User { get; set; }

    [Key, Column(Order = 1), ForeignKey("Friend")]
    public Guid FriendId { get; set; }
    public User Friend { get; set; }

    public DateTime DateCreated { get; set; }

}

用户存储库:

public class UserRepository : IUserRepository
{
    public User GetUserByName(string userName)
    {
        return context.Users.FirstOrDefault(u => u.Username == userName);
    }
}

如果我尝试使用此方法:

var userRepo = new UserRepository(new DataContext());
User user = userRepo.GetUserByName(User.Identity.Name); 

问题:user.Friends.first()。朋友返回null 如果我把它弄好了我的懒惰负荷不起作用。

请帮助...

指向项目的链接 - https://github.com/RanDahan/barker

1 个答案:

答案 0 :(得分:0)

User 类的构造函数中,您应该创建 Friends 集合的新实例

Friends = new HashSet<UserFriend>()

此外,我认为 UserFirends 中的导航属性也应该声明为虚拟。