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)

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);这句同时生成并播种数据库的

MVC 用基架创建Controller,通过数据库初始化器生成并播种数据库的更多相关文章

  1. Core开发-MVC 使用dotnet 命令创建Controller和View

    NET Core开发-MVC 使用dotnet 命令创建Controller和View   使用dotnet 命令在ASP.NET Core MVC 中创建Controller和View,之前讲解过使 ...

  2. MVC之基架

    参考 ASP.NET MVC5 高级编程(第5版) 定义: 通过对话框生成视图及控制器的模版,这个过程叫做“基架”. 基架可以为应用程序的创建.读取.更新和删除(CRUB)功能生成所需的样板代码.基架 ...

  3. ASP.NET Core开发-MVC 使用dotnet 命令创建Controller和View

    使用dotnet 命令在ASP.NET Core MVC 中创建Controller和View,之前讲解过使用yo 来创建Controller和View. 下面来了解dotnet 命令来创建Contr ...

  4. MVC使用基架添加控制器出现的错误:无法检索XXX的元数据

    环境 vs2012 框架 mvc3 数据库  sqlservercompact4.0 出现的错误如下: “ ---------------------------Microsoft Visual St ...

  5. 学习《ASP.NET MVC5高级编程》——基架

    基架--代码生成的模板.我姑且这么去定义它,在我学习微软向编程之前从未听说过,比如php代码,大部分情况下是我用vim去手写而成,重复使用的代码需要复制粘贴,即使后来我在使用eclipse这样的IDE ...

  6. Asp.net Mvc 数据库上下文初始化器

    在Asp.net Mvc 和Entity FrameWork程序中,如果数据库不存在,EF默认的行为是新建一个数据库.如果模型类与已有的数据库不匹配的时候,会抛出一个异常. 通过指定数据库上下文对象初 ...

  7. EF自动创建数据库步骤之四(启用数据库初始器)

    在创建完DBIfNotExistsInitializer数据库初始化器类后,需要在程序每一次访问数据库前,告诉EF使用该初始化器进行初始化. 代码如下 : Database.SetInitialize ...

  8. EF自动创建数据库步骤之三(自定义数据库初始器)

    EF自动创建数据库需要我们告诉数据库如何进行初始化:如创建表后是否需要插入一些基础数据,是否 需要创建存储过程.触发器等.还有就是EF有三种初始化方式(参见下面三个类): DropCreateData ...

  9. Entity Framework 数据库初始化的三种方法

    在数据库初始化产生时进行控制,有三个方法可以控制数据库初始化时的行为.分别为CreateDatabaseIfNotExists.DropCreateDatabaseIfModelChanges.Dro ...

随机推荐

  1. 【死磕Java并发】—–J.U.C之AQS(一篇就够了)

    [隐藏目录] 1 独占式 1.1 独占式同步状态获取 1.2 独占式获取响应中断 1.3 独占式超时获取 1.4 独占式同步状态释放 2 共享式 2.1 共享式同步状态获取 2.2 共享式同步状态释放 ...

  2. 【60.97%】【BZOJ 1925】 [Sdoi2010]地精部落

    Time Limit: 10 Sec  Memory Limit: 64 MB Submit: 1194  Solved: 728 [Submit][Status][Discuss] Descript ...

  3. [React Router v4] Render Multiple Components for the Same Route

    React Router v4 allows us to render Routes as components wherever we like in our components. This ca ...

  4. Android应用程序文件缓存getCacheDir()和getExternalCacheDir()

    如果Android引用程序需要缓存临时文件,系统提供了一个可管理的“内部缓存”和一个不可管理的“外部缓存”,分别调用getCacheDir()和getExternalCacheDir()方法,可以从当 ...

  5. Android Studio上手,基于VideoView的本地文件及流媒体播放器

    既然是第一个Android程序.少不了要Hello World. 1. 新建安卓project watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZm0wNTE ...

  6. JAVA 安装JDK注意事项

    在JAVA jdk安装的时候,文件夹名称最好不要有中文,有逗号,有下划线,空格等问题.这样easy出错,比方以下几个安装路径easy出错    java文件夹/jdk1.6_x86/    这样的就是 ...

  7. JAVA类(下)

    我看完了Java类,与C++相比,复杂了一点.其中有类的嵌套定义即内部类,枚举类等. 我看这两节花了我很多时间.其中有一些概念还是有点难懂. 下面,我详细总结内部类与枚举类. 内部类 内部类的主要作用 ...

  8. C++ 快速入门笔记:基本语法

    数据类型 枚举类型 enum color { red, green, blue } colors; colors = blue; 默认情况下,第一个名称的值是 0,后面的依次加 1.也可以自定初始值: ...

  9. 【b501】谁拿了最多的奖学金

    Time Limit: 1 second Memory Limit: 50 MB [问题描述] 某校的惯例是在每学期的期末考试之后发放奖学金.发放的奖学金共有五种,获取的条件各自不同:1) 院士奖学金 ...

  10. eclipse使用Hibernate tools反向工程插件遇到的几个问题

    1,在eclipse使用hibernate工具,生成hibernate配置文件时,可能会提示not parse ....xml错误 参见 加载本地dtd 2,反向工程中,生成配置文件时,一般要填写其默 ...