Asp.net mvc 4 首先在代码中以一对多关系在数据库表中插入数据

Asp.net mvc 4 首先在代码中以一对多关系在数据库表中插入数据,asp.net-mvc-4,ef-code-first,data-annotations,one-to-many,Asp.net Mvc 4,Ef Code First,Data Annotations,One To Many,我在Mvc4中使用代码优先的方法。对于身份验证和授权,使用简单的成员身份。 我的UserProfile类具有这些字段,其中用户可以有多个帖子和评论 [Table("UserProfile")] public class UserProfile { public UserProfile() { this.PostComments = new HashSet<PostComment>(); this.Posts = new HashSe

我在Mvc4中使用代码优先的方法。对于身份验证和授权,使用简单的成员身份。 我的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; }
}
当我试着调试这个动作方法时,我发现它在这一行传递null---

如何将当前loggedIn用户名传递到数据库。 我想分享的另一个信息是-- 在Sql Server中,它正在创建5列---- PostId(主键), 消息,PostedBy(int),PostedDate,UserProfile\u UserId(外键列)。 现在,一切正常,但在UserProfile\u UserId列中,它存储空值。 我知道它不应该为空,但如何为空。 我缺少什么。我应该怎么做。使用dbFirst方法对代码进行了细微的更改,代码运行良好

要在查看页面上获取帖子,操作方法为----


这是我想用用户名显示post和comment的操作方法。这里,PostedByName返回null。

您的模型中没有
int UserProfile\u UserId
属性(如何设置它)@StephenMuecke那么我应该手动定义fk字段并手动返回该列的值以存储在数据库中还是实体框架将自动插入该值如果我理解正确,
PostedBy
UserProfile\u UserId
相同?你们两个都需要吗?是的,我认为postedBy和UserProfile\uUserId是一样的。但是,我不知道是否应该同时有这两个列。我已经编辑了我的问题,还包括了post的Get方法。它给出了System.NullReferenceException。在post的Get方法中,当我调试它时,它在PostedByName属性处返回null@StephenMuecke@StephenMuecke你可以看看这段代码。它是DbFirst方法。我已经将它们转换为代码优先
   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; }
}
   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);
        }
    }
  PostedByName = usr.UserName
    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;
    }