首先在代码中以一对多的关系在数据库表中插入数据

时间:2015-10-20 07:43:41

标签: asp.net-mvc-4 ef-code-first data-annotations one-to-many

我正在使用Mvc4的Code First Approach。对于身份验证和授权,正在使用简单的成员资格。 我的UserProfile类具有这些字段,用户可以在其中拥有多个帖子和评论。

  [Table("UserProfile")]
public class UserProfile
{
    public UserProfile()
    {
        this.PostComments = new HashSet<PostComment>();
        this.Posts = new HashSet<Post>();
    }
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string AvatarExt { get; set; }
    public virtual ICollection<PostComment> PostComments { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

和我的Post类是这样的。我在userprofile类和Post类之间配置了一对多的关系。

   public class Post
  {
    public Post()
    {
        this.PostComments = new HashSet<PostComment>();
    }
    [Key]
    public int PostId { get; set; }
    public string Message { get; set; }
    public int PostedBy { get; set; }
    public System.DateTime PostedDate { get; set; }
    public virtual ICollection<PostComment> PostComments { get; set; }
    public virtual UserProfile UserProfile { get; set; }
}

这是我的控制器的操作方法,用于将帖子添加到数据库中的post表。

   public HttpResponseMessage PostPost(Post post)
    {
        post.PostedBy = WebSecurity.CurrentUserId;
        post.PostedDate = DateTime.UtcNow;
       // post.UserProfile.UserId = WebSecurity.CurrentUserId;
        ModelState.Remove("post.PostedBy");
        ModelState.Remove("post.PostedDate");
      //  ModelState.Remove("post.UserProfile.UserId");

        if (ModelState.IsValid)
        {
            db.Posts.Add(post);
            db.SaveChanges();
            var usr = db.UserProfiles.FirstOrDefault(x => x.UserId == post.PostedBy);
            var ret = new
            {
                Message = post.Message,
                PostedBy = post.PostedBy,
                PostedByName = usr.UserName,
                PostedByAvatar = imgFolder + (String.IsNullOrEmpty(usr.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt),
                PostedDate = post.PostedDate,
                PostId = post.PostId
            };
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = post.PostId }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

当我尝试调试此动作方法时,我发现它在此行传递null ---

  PostedByName = usr.UserName

如何将当前的loggedIn userName传递给数据库。 我要分享的另一个信息是 - 在Sql Server中,它创建了5列---- PostId(主键), 消息,PostedBy(int),PostedDate,UserProfile_UserId(外键列)。 现在,一切正常,但在UserProfile_UserId列中,它存储为null。 我知道它不应该是空的但是如何。 我缺少什么。我应该怎么做。使用dbFirst方法对此代码进行了细微更改,并且该代码工作正常。

要在视图页面上发帖,操作方法是----

    public dynamic GetPosts()
    {

        var ret = (from post in db.Posts.ToList()
                   orderby post.PostedDate descending
                   select new
                   {
                       Message = post.Message,
                       PostedBy = post.PostedBy,
                       PostedByName = post.UserProfile.UserName,
                       PostedByAvatar = imgFolder + (String.IsNullOrEmpty(post.UserProfile.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt),
                       PostedDate = post.PostedDate,
                       PostId = post.PostId,
                       PostComments = from comment in post.PostComments.ToList()
                                      orderby comment.CommentedDate
                                      select new
                                      {
                                          CommentedBy = comment.CommentedBy,
                                          CommentedByName = comment.UserProfile.UserName,
                                          CommentedByAvatar = imgFolder + (String.IsNullOrEmpty(comment.UserProfile.AvatarExt) ? defaultAvatar : comment.CommentedBy + "." + comment.UserProfile.AvatarExt),
                                          CommentedDate = comment.CommentedDate,
                                          CommentId = comment.CommentId,
                                          Message = comment.Message,
                                          PostId = comment.PostId

                                      }
                   }).AsEnumerable();
        return ret;
    }

这是我想用他们的UserName显示帖子和评论的动作方法。在这里,PostedByName返回null。

0 个答案:

没有答案