无法插入我的数据库

时间:2016-11-25 19:42:53

标签: c# asp.net-mvc entity-framework

这是我第一次使用EF而且我一直在用这个来敲打我的脑袋。

基本上,我只是尝试使用视图中的提交表单和控制器中的create方法向数据库添加记录。

基本上,我有一个非常基本的模型和一个带Create方法的控制器

以下是代码:

带有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; }
        }
    }
}

控制器:

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");
        }
    }
}

我的View是一个标准的自动生成Create,它有两个输入字段(我假设id是从db生成的),基于模型。

@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>

1 个答案:

答案 0 :(得分:4)

您需要调用db.SaveChanges