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
對象。
請問,我該如何做到這一點?
優秀! 它工作完美。 :) – kooldave98