2012-09-27 106 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