5

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 ?

1 Answer 1

10

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();
   }
Sign up to request clarification or add additional context in comments.

1 Comment

doesn't attaching the user to the context result in a db call? Is there any way to insert a object with related entities in one round trip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.