public void AddPost(Post post) { using (var connection = new SqlConnection(_connectionString)) using (var cmd = connection.CreateCommand()) { cmd.CommandText = "INSERT INTO Posts (Content, Date, Title) VALUES (@content, @date, @title); SELECT @@Identity"; cmd.Parameters.AddWithValue("@content", post.Content); cmd.Parameters.AddWithValue("@date", post.Date); cmd.Parameters.AddWithValue("@title", post.Title); connection.Open(); post.Id = (int)(decimal)cmd.ExecuteScalar(); } }
public ActionResult AddPost(string content, string title, string tags) { var db = new BlogDb(@"Data Source=.\sqlexpress;Initial Catalog=Blog;Integrated Security=True"); Post post = new Post { Content = content, Title = title, Date = DateTime.Now }; db.AddPost(post); db.AddTagsToPost(tags, post.Id); return RedirectToAction("Index"); }
public ActionResult AddPost(string title, string text, string tags) { var db = new BlogDb(_connectionString); var post = new Post { Date = DateTime.Now, Text = text, Title = title }; db.AddPost(post); IEnumerable<Tag> postTags = tags.Split(',').Select(t => { int tagId = db.AddTag(t); return new Tag { Id = tagId, Name = t }; }); db.AddTagsToPost(post, postTags); return RedirectToAction("Index", "Blog"); }
private Post GetPostFromReader(SqlDataReader reader) { Post post = new Post(); post.Id = (int)reader["Id"]; post.Text = (string)reader["Text"]; post.Date = (DateTime)reader["Date"]; post.Title = (string)reader["Title"]; return post; }
public void AddTagsToPost(Post p, IEnumerable<Tag> tags) { using (var connection = new SqlConnection(_connectionString)) using (var cmd = connection.CreateCommand()) { cmd.CommandText = "INSERT INTO PostsTags (PostId, TagId) VALUES (@postId, @tagId)"; connection.Open(); foreach (Tag tag in tags) { cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@postId", p.Id); cmd.Parameters.AddWithValue("@tagId", tag.Id); cmd.ExecuteNonQuery(); } } }