我是Entity Framework的新手,我需要将一个具有相关FK对象Comment
的对象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语句中指定我的'User'的PK。
我试图对Entity Framework做同样的事情,但似乎没有用。首先从数据库中获取User
对象只是为了插入一个新的“注释”,这样就太过分了。
拜托,我怎么能实现这个目标?
答案 0 :(得分: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();
}