koo*_*e98 4 entity-framework-4 c#-4.0
我是Entity Framework的新手,我需要将一个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();
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,使用T-SQL,如果我知道User对象的PRIMARY KEY ,我可以插入我的Comment对象并在insert语句中指定我的'User'的PK.
我试图对Entity Framework做同样的事情,它似乎不起作用.首先User从数据库中获取对象只是为了插入一个新的"注释" ,这样做太过分了.
拜托,我怎么能实现这个目标?
您需要将用户对象附加到上下文,以便上下文知道其现有实体
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();
}
Run Code Online (Sandbox Code Playgroud)