Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Insert object with related object

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

    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 have tried to do the same with Entity Framework and it doesn't seem to work. It would be overkill to have to first fetch the User object from the database just to insert a new 'Comment'.

Please, how can I achieve this ?

like image 309
sacritruth Avatar asked Dec 27 '22 17:12

sacritruth


1 Answers

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

  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();
   }
like image 60
Eranga Avatar answered Feb 12 '23 10:02

Eranga