I have a method that creates some entry in database and returnes it's Id. I would like to somehow separate these two because it violates Command-Query Separation.
e.g. method (simplified):
int CreatePost(database::Post newPost)
{
using(var db = new database::MainModelContainer())
{
db.Posts.Add(newPost);
db.SaveChanges();
return newPost.Id;
}
}
I know there is workaround using ref or out but I consider those solutions unclean. I would like to have command with following signature.
void CreatePost(database::Post newPost)
Is there a way I could accomplish this ?
Note:
I need to know what is the Id of newly created entry immediately after it was created.
This could be solved with a memento pattern, except that you don't seem to need all of the undo-ability that comes with the memento. Something simple to capture the state of the
Post
object after it has been inserted would work:Each time you create a new post, you will construct one of these creators to do it for you. You can query the
CreatedPostId
property at any time without concern of affecting state.