【问题标题】:Entity Framework Insert object with related object实体框架插入具有相关对象的对象
【发布时间】:2012-09-27 09:00:16
【问题描述】:

我是 Entity Framework 的新手,我需要将具有相关 FK 对象 User 的对象 Comment 插入到数据库中。

    public Class Comment
    {
        public int CommentID { get; set; }
        public string CommentContent { get; set; }
        public virtual User User { get; set; }
        public virtual DateTime CommentCreationTime { get; set; }
    }

public class User
{      

    public int UserID { get; set; }
    public string UserName { get; set; }
    public string UserPassword { get; set; }

    public string UserImageUrl{get; set;}
    public DateTime UserCreationDate { get; set; }

    public virtual List<Comment> Comments { get; set; }
}

  public void AddComment()
  {
        User user = new User() { UserID = 1 };            
        Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };

        var ctx = new WallContext();
        comments = new CommentsRepository(ctx);

        comments.AddComment(comment);
        ctx.SaveChanges();
   }

理想情况下,使用 T-SQL,如果我知道我的 User 对象的主键,我可以插入我的 Comment 对象并在插入语句中指定我的“用户”的 PK。

我尝试对 Entity Framework 做同样的事情,但它似乎不起作用。必须首先从数据库中获取User 对象才能插入新的“评论”,这将是矫枉过正。

请问,我怎样才能做到这一点?

【问题讨论】:

    标签: c#-4.0 entity-framework-4


    【解决方案1】:

    您需要将用户对象附加到上下文,以便上下文知道其现有实体

      public void AddComment()
      {
           var ctx = new WallContext();
    
            User user = new User() { UserID = 1 };  
    
            ctx.Users.Attach(user);
    
            Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };
    
            comments = new CommentsRepository(ctx);
    
            comments.AddComment(comment);
            ctx.SaveChanges();
       }
    

    【讨论】:

    • 不会将用户附加到上下文导致 db 调用?有没有办法在一次往返中插入具有相关实体的对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多