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