Is there something wrong with this linq insert? It seems a lot of SQL for simple work

I am new to the way of doing MVC / C # / Linq tasks.

It seems really inefficient. Am I doing something wrong or am I mistaken in any assumptions?

For example, adding a new message to the forum thread might look something like this:

    public ActionResult AddNewPost(int userID, int threadID, string content)
    {
        User user = DataContext.Users.FirstOrDefault(u => u.ID == userID);
        Thread thread = DataContext.Threads.Include(t => t.Posts).FirstOrDefault(t => t.ID == threadID);
        Post post = new Post()
        {   
            Content = content,
            User = user
        }
        thread.Posts.Add(post);
        DataContext.SaveChanges();
    }

Now, backstage, this generates a lot of sql for:

  • select all stream details.
  • plus all the messages in this thread (maybe quite a lot)
  • it also selects all user data.

, INSERT. Posts, threadID userID, . , asp php , :

INSERT into forum_posts (threadID, postID, content) VALUES (threadID, postID, 'content')

- MVC ?

, . :

    public class Post
    {
        User User {get;set;}
        Thread Thread {get;set;}
        string Content {get;set;}
    }

:

    public class Post
    {
        User User {get;set;}
        UserID UserID {get;set;}
        Thread Thread {get;set;}
        ThreadID ThreadID {get;set;}
        string Content {get;set;}
    }

:

        Post post = new Post()
        {   
            Content = content,
            UserID = userID,
            ThreadID = threadID,
        }
        DataContext.Posts.Add(post);

User Thread , , : Post.User.UserName.

ID , .

?

+3
1

    Post post = new Post()
    {   
        Content = content,
        userID = userID,
        threadID = threadID
    }

    DataContext.Posts.Add(post);
    DataContext.SaveChanges();

UPDATE: , , UserID ThreadID.

public class Post
{
    [ForeignKey("User")]
    UserID UserID {get;set;}
    User User {get;set;}

    [ForeignKey("Thread")]
    ThreadID ThreadID {get;set;}
    Thread Thread {get;set;}

    string Content {get;set;}
}
+4

All Articles