0

I'm sittin' with my final project on the school, but have some trouble finishing it.

First of all I have made a Webstore with help from following tutorial. It's a tutorial based on MVC 3, but I made it for newest version.

Afterwards I wanted to make some kind of blog-post database based on the same principles and this is where I'm in trouble.

I have made the Article as a model:

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

Afterwards I created the 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; }
    }

Then I created the NewsEntities DbContext:

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

Finally I filled following in to a "NewsData" class:

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

Then I created a NewsManagerController using Entity Framework. When I run my application, and will create a new articles the Subject-dropdown is empty. I have been looking all night for a solution without any luck.

I hope you can help me out! Feel free to ask for more code snippets or information.

Thanks!

//refnedergaard

EDIT:

Controller:

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

Create-view:

    @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>
3
  • 1
    Show us the relevant action method and view code for the create form Commented Feb 15, 2016 at 21:17
  • What Subject-dropdown You need to show the relevant code (the controller and the view) Commented Feb 15, 2016 at 23:49
  • I have added the controller and the create view to the post. Thanks for your help, appreciate it! Commented Feb 16, 2016 at 7:57

2 Answers 2

1

You created a list of subjects to add to your context, but you never save the seed data into your context. You could try:

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" }
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think your issue is because you are not saving to your DB your list of ArticleSubject. You need to add them first the ArticleSubjects DbSet and them call SaveChanges method of your context:

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

Now, if you use Migration, you are not going to drop your DB in case that your model change, so you might want to use the @Sam variant to avoid duplicates.

Also, in order to execute your custom initializer, you have to set the DB Initializer via Database property:

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

    public NewsEntities()
    {
      Database.SetInitializer(new NewsData());
    }
}

2 Comments

Well, I tried the "@sam way" and added your public NewsEntities() brackets. I didn't get any out of it. When I tried with breakpoint and step-by-step it never showed med NewsData.cs for some reason.
NOW! I used the context.ArticleSubjects.AddRange(articleSubjects); context.SaveChanges() So you were right only because I didn't saved the data. Thanks for your help, appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.