Robert Ross Robert Ross - 8 days ago 6
C# Question

Unable to insert into my database

It's my first time using EF and I've been banging my head with this more then I have to.

Basically, I am simply trying to add a record to the database with using a submit form in the view and a create method in the controller.

So basically, I have a very basic model and a controller with a

Create
method

Here is the code :

Model with
DbContext
:

using System.Data.Entity;

namespace class_project.Models
{
public class Post
{
public int PostId { get; set; }
[Required(ErrorMessage = "no!")]
public string Title { get; set; }
[Required(ErrorMessage = "no!")]
public string Content { get; set; }

public Post(int PostId, string Title, string Content)
{
this.PostId = PostId;
this.Title = Title;
this.Content = Content;
}

public Post()
{ }

public class PostContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
}
}


Controller :

using static class_project.Models.Post; // I AM NOT SURE ABOUT THIS PART, BUT IT WAS ABLE TO BUILD WHEN ADDED IT.

namespace class_project.Controllers
{
public class PostsController : Controller
{
private PostContext db = new PostContext();

public ActionResult Create(Post obj)
{
if (!ModelState.IsValid)
{
return View(obj);
}

db.Posts.Add(obj);

return RedirectToAction("Index", "Posts");
}
}
}


And my
View
is a standard autogenerated
Create
with two input fields (I assume that the id is generated from the db) based on the model.

@model class_project.Models.Post

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Post</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Answer

You need to call db.SaveChanges

Comments