实体框架插入具有相关对象的对象

时间:2012-09-27 09:00:16

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

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

    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对象的PRIMARY KEY,我可以插入我的Comment对象并在insert语句中指定我的'User'的PK。

我试图对Entity Framework做同样的事情,但似乎没有用。首先从数据库中获取User对象只是为了插入一个新的“注释”,这样就太过分了。

拜托,我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:9)

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

  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();
   }