在多对多表中添加数据

问题描述 投票:1回答:1

我刚刚开始学习编写代码,我必须创建一个包含书籍和作者的应用程序。我创建了3本表书,作者和book_by_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);
        }
    }
}
c# sql .net visual-studio .net-framework-version
1个回答
0
投票

我之前没有使用过System.Web.Mvc,但我想我仍然可以帮助你入门。我将首先关注从数据库中查询数据。你正在寻找一个Authors列表,所以你需要一个DB查询,如:SELECT id, name FROM authors

这将从authors表中检索所有行,每行包含idname。幸运的是,您正在使用可以为您执行此操作的Web框架,您甚至可以获得一个示例。

查看当前代码,我们可以看到如何在模型中定义Books,这些模型表示C#中“a Book”的数据库表示,以及如何在Book控制器中检索它们并将其传递给View进行渲染:

View(db.books.ToList());

这与你想要用Author做的完全类似!

© www.soinside.com 2019 - 2024. All rights reserved.