使用DbContext添加信息 - ASP.NET MVC

时间:2016-02-15 21:14:23

标签: asp.net asp.net-mvc entity-framework code-first dbcontext

我坐着'我在学校的最后一个项目,但在完成它时遇到了一些麻烦。

首先,我在以下tutorial的帮助下创建了一个Webstore。这是一个基于MVC 3的教程,但是我用它来制作最新版本。

之后我想根据相同的原则制作某种博客文章数据库,这就是我遇到麻烦的地方。

我已将该文章作为模型:

public class Article
{
    [Key]
    public int ArticleId { get; set; }
    public int SubjectId { get; set; }
    public string Title { get; set; }
    public string MainText { get; set; }
    public string PictureURL { get; set; }
    public ArticleSubject ArticleSubject { get; set; }
}

之后我创建了ArticleSubject:

public class ArticleSubject
    {
        [Key]
        public int SubjectId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public List<Article> Articles { get; set; }
    }

然后我创建了NewsEntities DbContext:

public class NewsEntities : DbContext
{
    public DbSet<Article> Articles { get; set; }
    public DbSet<ArticleSubject> ArticleSubjects { get; set; }
}

最后,我填写了一个&#34; NewsData&#34;类:

public class NewsData : DropCreateDatabaseIfModelChanges<NewsEntities>
{
    protected override void Seed(NewsEntities context)
    {
        var articleSubjects = new List<ArticleSubject>
        {
            new ArticleSubject { Title = "Almindelige Nyheder" },
            new ArticleSubject { Title = "Arrangementer" },
            new ArticleSubject { Title = "Udstillinger" }
        };
    }
}

然后我使用Entity Framework创建了一个NewsManagerController。当我运行我的应用程序,并将创建一个新文章时,主题下拉列表为空。我一直在寻找一个没有运气的解决方案。

我希望你能帮助我!您可以随意索取更多代码段或信息。

谢谢!

// refnedergaard

编辑:

控制器:

public class NewsManagerController : Controller
{
    private NewsEntities db = new NewsEntities();

    // GET: NewsManager
    public ActionResult Index()
    {
        var articles = db.Articles.Include(a => a.ArticleSubject);
        return View(articles.ToList());
    }

    // GET: NewsManager/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Article article = db.Articles.Find(id);
        if (article == null)
        {
            return HttpNotFound();
        }
        return View(article);
    }

    // GET: NewsManager/Create
    public ActionResult Create()
    {
        ViewBag.SubjectId = new SelectList(db.ArticleSubjects, "SubjectId", "Title");
        return View();
    }

    // POST: NewsManager/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ArticleId,SubjectId,Title,MainText,PictureURL")] Article article)
    {
        if (ModelState.IsValid)
        {
            db.Articles.Add(article);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.SubjectId = new SelectList(db.ArticleSubjects, "SubjectId", "Title", article.SubjectId);
        return View(article);
    }

    // GET: NewsManager/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Article article = db.Articles.Find(id);
        if (article == null)
        {
            return HttpNotFound();
        }
        ViewBag.SubjectId = new SelectList(db.ArticleSubjects, "SubjectId", "Title", article.SubjectId);
        return View(article);
    }

    // POST: NewsManager/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ArticleId,SubjectId,Title,MainText,PictureURL")] Article article)
    {
        if (ModelState.IsValid)
        {
            db.Entry(article).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.SubjectId = new SelectList(db.ArticleSubjects, "SubjectId", "Title", article.SubjectId);
        return View(article);
    }

    // GET: NewsManager/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Article article = db.Articles.Find(id);
        if (article == null)
        {
            return HttpNotFound();
        }
        return View(article);
    }

    // POST: NewsManager/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Article article = db.Articles.Find(id);
        db.Articles.Remove(article);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

创建视图:

    @model boerglumklosterdk.Models.Article

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

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

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

        <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.MainText, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MainText, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MainText, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PictureURL, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PictureURL, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PictureURL, "", 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>

2 个答案:

答案 0 :(得分:1)

您创建了要添加到上下文中的主题列表,但您从未将种子数据保存到上下文中。你可以尝试:

public class NewsData : DropCreateDatabaseIfModelChanges<NewsEntities>
{
    protected override void Seed(NewsEntities context)
    {
        context.ArticleSubjects.AddOrUpdate(
            p => p.Title,
            new ArticleSubject { Title = "Almindelige Nyheder" },
            new ArticleSubject { Title = "Arrangementer" },
            new ArticleSubject { Title = "Udstillinger" }
        );
    }
}

答案 1 :(得分:0)

我认为您的问题是因为您没有将ArticleSubject列表保存到您的数据库中。您需要先在ArticleSubjects DbSet中添加它们,然后调用上下文的SaveChanges方法:

context.ArticleSubjects.AddRange(articleSubjects);
context.SaveChanges();

现在,如果您使用Migration,则在模型更改的情况下,您不会丢弃数据库,因此您可能希望使用@Sam变体来避免重复。

此外,为了执行自定义初始值设定项,您必须通过Initializer属性设置数据库Database

public class NewsEntities : DbContext
{
    public DbSet<Article> Articles { get; set; }
    public DbSet<ArticleSubject> ArticleSubjects { get; set; }

    public NewsEntities()
    {
      Database.SetInitializer(new NewsData());
    }
}
相关问题