在多对多表中添加数据

时间:2019-03-05 13:01:58

标签: c# sql .net visual-studio .net-framework-version

我刚刚开始学习工作中的编码,我必须创建一个包含书籍和作者的应用程序。我创建了3个表book,author和book_by_author。我已在author表中添加了一些数据,并且必须创建一个用于为该书添加数据的视图,但是在我写完书名后应从下拉列表中选择作者。 Check picture 问题是我不知道该怎么做,我不应该写什么代码。

数据库代码:

CREATE TABLE [dbo].[book] (
    [Id]    INT           IDENTITY (0, 1) NOT NULL,
    [title] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

CREATE TABLE [dbo].[author] (
    [Id]   INT           IDENTITY (0, 1) NOT NULL,
    [name] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

CREATE TABLE [dbo].[book_by_author] (
    [Id_author] INT NOT NULL,
    [Id_book]   INT NOT NULL,
    CONSTRAINT [FK_book_by_author_ToTableAuthor] FOREIGN KEY ([Id_author]) REFERENCES [dbo].[author] ([Id]),
    CONSTRAINT [FK_book_by_author_ToTableBook] FOREIGN KEY ([Id_book]) REFERENCES [dbo].[book] ([Id])
);

型号代码:

namespace MVC.Models
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;

    public partial class book
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public book()
        {
            this.authors = new HashSet<author>();
        }

        public int Id { get; set; }
        public string title { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<author> authors { get; set; }
    }
}

namespace MVC.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    public partial class author
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public author()
        {
            this.books = new HashSet<book>();
        }

        public int Id { get; set; }
        [DisplayName("Author name")]
        public string name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<book> books { get; set; }
    }
}

控制器代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SchaefflerBibliothèque_MVC.Models;

namespace SchaefflerBibliothèque_MVC.Controllers
{
    public class booksController : Controller
    {
        private librarydbEntities db = new librarydbEntities();

        // GET: books
        public ActionResult Index()
        {
            return View(db.books.ToList());
        }

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

        // GET: books/Create
        public ActionResult Create()
        {
            ViewBag.AuthorSelect = db.authors.Where(n => n.name != null).Select(n => new SelectListItem
            {
                Text = n.name,
            });
            return View();
        }

        // POST: books/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,title")] book book)
        {
            if (ModelState.IsValid)
            {
                db.books.Add(book);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(book);
        }

        // GET: books/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            book book = db.books.Find(id);
            if (book == null)
            {
                return HttpNotFound();
            }
            return View(book);
        }

        // POST: books/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,title")] book book)
        {
            if (ModelState.IsValid)
            {
                db.Entry(book).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(book);
        }

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

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

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

1 个答案:

答案 0 :(得分:0)

我以前没有使用过System.Web.Mvc,但是我认为我仍然可以帮助您入门。我将首先关注从数据库查询数据。您正在寻找Author的列表,因此您需要一个类似SELECT id, name FROM authors的数据库查询。

这将从authors表中检索所有行,每行分别具有和idname。幸运的是,您正在使用可以为您执行此操作的Web框架,甚至手头都有一个示例。

看看您当前的代码,我们可以看到如何在模型中定义Book,这些模型在C#中代表“一本书”的数据库表示形式,以及如何在Book控制器中检索它们并将其传递给View用于渲染:

View(db.books.ToList());

这完全类似于您要使用Author做的事情!