MVC 用基架创建Controller,通过数据库初始化器生成并播种数据库

时间:2023-03-09 20:26:00
MVC 用基架创建Controller,通过数据库初始化器生成并播种数据库

1 创建MVC应用程序

2 在Model里面创建实体类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MyMusicStore.Models

{

    public class Album

    {

        public virtual int AlbumId { get; set; }

        public virtual int GenreId { get; set; }

        public virtual int ArtistId { get; set; }

        public virtual string Title { get; set; }

        public virtual decimal Price { get; set; }

        public virtual string AlbumArtUrl { get; set; }

        public virtual Genre Genre { get; set; }

        public virtual Artist Artist { get; set; }

    }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MvcMusicStore.Models

{

    public class Artist

    {

        public virtual int ArtistId { get; set; }

        public virtual string Name { get; set; }

    }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MyMusicStore.Models

{

    public class Genre

    {

        public virtual int GenreId { get; set; }

        public virtual string Name { get; set; }

        public virtual string Description { get; set; }

        public virtual List<Album> Albums { get; set; }

    }

}

3 添加数据库连接字符串

<add name="MusicStoreDB" connectionString="database=MusicStore;uid=sa;pwd=Server2012" providerName="System.Data.SqlClient"/>

4 创建数据操作类

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

namespace MyMusicStore.Models

{

    public class MusicStoreDB:DbContext

    {

        public MusicStoreDB() : base("name=MusicStoreDB")

        {

        }

public DbSet<Album> Albums { get; set; }

        public DbSet<Artist> Artists { get; set; }

public DbSet<Genre> Genres { get; set; }

    }

}

5 创建数据库初始化器

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MyMusicStore.Models

{

    public class MusicStoreDbInitializer:System.Data.Entity.DropCreateDatabaseAlways<MusicStoreDB>

    {

        protected override void Seed(MusicStoreDB context)

        {

            context.Artists.Add(new Artist { Name = "Al Di Meola" });

            context.Genres.Add(new Genre { Name = "Jazz" });

            context.Albums.Add(new Album

            {

                Genre = new Genre { Name = "Rock" },

                Artist = new Artist { Name = "Rush" },

                Price = 9.99m,

                Title = "Caravan"

            });

            base.Seed(context);

        }

    }

}

6 设置数据库初始化器

using MyMusicStore.Models;

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Optimization;

using System.Web.Routing;

namespace MyMusicStore

{

    public class MvcApplication : System.Web.HttpApplication

    {

        protected void Application_Start()

        {

            Database.SetInitializer(new MusicStoreDbInitializer());

AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }

    }

}

7 根据基架创建Controller(包含视图的MVC5控制器使用EF)

MVC 用基架创建Controller,通过数据库初始化器生成并播种数据库

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Linq;

using System.Net;

using System.Web;

using System.Web.Mvc;

using MyMusicStore.Models;

namespace MyMusicStore.Controllers

{

    public class StoreManagerController : Controller

    {

        private MusicStoreDB db = new MusicStoreDB();

// GET: StoreManager

        public ActionResult Index()

        {

            var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);

            return View(albums.ToList());

        }

// GET: StoreManager/Details/5

        public ActionResult Details(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Album album = db.Albums.Find(id);

            if (album == null)

            {

                return HttpNotFound();

            }

            return View(album);

        }

// GET: StoreManager/Create

        public ActionResult Create()

        {

            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name");

            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name");

            return View();

        }

// POST: StoreManager/Create

        // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 

        // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Create([Bind(Include = "AlbumId,GenreId,ArtistId,Title,Price,AlbumArtUrl")] Album album)

        {

            if (ModelState.IsValid)

            {

                db.Albums.Add(album);

                db.SaveChanges();

                return RedirectToAction("Index");

            }

ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);

            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);

            return View(album);

        }

// GET: StoreManager/Edit/5

        public ActionResult Edit(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Album album = db.Albums.Find(id);

            if (album == null)

            {

                return HttpNotFound();

            }

            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);

            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);

            return View(album);

        }

// POST: StoreManager/Edit/5

        // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 

        // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Edit([Bind(Include = "AlbumId,GenreId,ArtistId,Title,Price,AlbumArtUrl")] Album album)

        {

            if (ModelState.IsValid)

            {

                db.Entry(album).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);

            ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);

            return View(album);

        }

// GET: StoreManager/Delete/5

        public ActionResult Delete(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Album album = db.Albums.Find(id);

            if (album == null)

            {

                return HttpNotFound();

            }

            return View(album);

        }

// POST: StoreManager/Delete/5

        [HttpPost, ActionName("Delete")]

        [ValidateAntiForgeryToken]

        public ActionResult DeleteConfirmed(int id)

        {

            Album album = db.Albums.Find(id);

            db.Albums.Remove(album);

            db.SaveChanges();

            return RedirectToAction("Index");

        }

protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                db.Dispose();

            }

            base.Dispose(disposing);

        }

    }

}

8 访问http://localhost:3438/StoreManager,是在访问Index() 方法里的 var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);这句同时生成并播种数据库的