2012-09-27 104 views
4

我是一个新手与实体框架,我需要插入一个对象Comment有一个相关的FK对象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语句中我的“用户”的PK。

我试图用实体框架做同样的事情,它似乎没有工作。如果仅仅为了插入一个新的'Comment',就必须首先从数据库中取出User对象。

请问,我该如何做到这一点?

回答

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

优秀! 它工作完美。 :) – kooldave98