【发布时间】:2012-09-27 09:00:16
【问题描述】:
我是 Entity Framework 的新手,我需要将具有相关 FK 对象 User 的对象 Comment 插入到数据库中。
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 对象的主键,我可以插入我的 Comment 对象并在插入语句中指定我的“用户”的 PK。
我尝试对 Entity Framework 做同样的事情,但它似乎不起作用。必须首先从数据库中获取User 对象才能插入新的“评论”,这将是矫枉过正。
请问,我怎样才能做到这一点?
【问题讨论】: