设为首页 加入收藏

TOP

asp.net core系列 40 Web 应用MVC 介绍与详细示例(二)
2019-09-17 18:24:48 】 浏览:46
Tags:asp.net core 系列 Web 应用 MVC 介绍 详细 示例
存数据库一起使用, 这对测试非常有用。

    PM> Install-Package Microsoft.EntityFrameworkCore.InMemory

 

  2.2 新建数据模型类(POCO )和EF上下文类

    public class MvcMovieContext : DbContext
    {
        public MvcMovieContext(DbContextOptions options)
            : base(options)
        {
        }
        public DbSet<Movie> Movie { get; set; }
    }    
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

 

   2.3 初始化数据

     public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    //var context = services.GetRequiredService<MvcMovieContext>();
                    //程序运行时,使用EF迁移生成数据,用在关系型数据库
                    //context.Database.Migrate();
SeedData.Initialize(services); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
    public static class SeedData
    {
        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="serviceProvider"></param>
        public static  void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcMovieContext(
                serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
            {
                // 如果有数据返回
                if (context.Movie.Any())
                {
                    return;   // DB has been seeded
                }

                context.Movie.AddRange(
                    new Movie
                    {
                        Title = "When Harry Met Sally",
                        ReleaseDate = DateTime.Parse("1989-2-12"),
                        Genre = "Romantic Comedy",
                        Price = 7.99M
                    },

                    new Movie
                    {
                        Title = "Ghostbusters ",
                        ReleaseDate = DateTime.Parse("1984-3-13"),
                        Genre = "Comedy",
                        Price = 8.99M
                    },

                    new Movie
                    {
                        Title = "Ghostbusters 2",
                        ReleaseDate = DateTime.Parse("1986-2-23"),
                        Genre = "Comedy",
                        Price = 9.99M
                    },

                    new Movie
                    {
                        Title = "Rio Bravo",
                        ReleaseDate = DateTime.Parse("1959-4-15"),
                        Genre = "Western",
                        Price = 3.99M
                    }
                );
                context.SaveChanges();
            }
        }
    }
View Code

  

  2.4 添加控制器类(MoviesController)

  public class MoviesController : Controller
    {

        private readonly  MvcMovieContext _MvcMovieContext;

        public MoviesController(MvcMovieContext MvcMovieContext)
        {
            this._MvcMovieContext = MvcMovieContext;
        }
    }

 

  2.5 列表页Movies/index.cshtml

        // GET: /<controller>/
        public IActionResult Index()
        {
            var movies = _MvcMovieContext.Movie.ToList();
            return View(movies);
        }
@model IEnumerable<StudyMVCDemo.Models.Movie>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ReleaseDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Genre)
            </th>
            <th>
                @Html.Di
首页 上一页 1 2 3 4 5 下一页 尾页 2/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇学习ASP.NET Core Razor 编程系列.. 下一篇ASP.NET Core 使用 SignalR 遇到..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目