Entity Framework Insert Object with Related Object

I am new to Entity Framework and I need to insert a Comment object into the database that has an associated FK User object.

  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(); } 

Ideally, with T-SQL, if I know the PRIMARY KEY of my User object, I could just insert my Comment object and specify the PK of my "User" in the insert statement.

I tried to do the same with Entity Framework and it doesn't seem to work. It would be redundant to first extract the User object from the database to insert a new "Comment".

Please, how can I achieve this?

+4
source share
1 answer

You need to attach the user object to the context so that the context knows its existing object

  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(); } 
+9
source

Source: https://habr.com/ru/post/1436552/


All Articles