【问题标题】:Add data in many to many tables在多对多表中添加数据
【发布时间】:2019-03-05 13:01:57
【问题描述】:

我刚开始在工作中学习编码,我必须创建一个包含书籍和作者的应用程序。我创建了 3 个表 book、author 和 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】:

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

    这将从authors 表中检索所有行,每行具有idname。幸运的是,您正在使用可以为您完成此任务的 Web 框架,而且您手头甚至还有一个示例。

    查看您当前的代码,我们可以看到 Books 在 C# 中表示“一本书”的数据库表示的模型中是如何定义的,以及它们是如何在 Book 控制器中检索并传递给视图进行渲染的:

    View(db.books.ToList());
    

    这完全类似于您要对 Author 执行的操作!

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 2017-07-09
      • 1970-01-01
      • 2010-10-10
      • 2012-09-16
      相关资源
      最近更新 更多