我无法在第一个ASP.NET CORE APP上播种数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我无法在第一个ASP.NET CORE APP上播种数据相关的知识,希望对你有一定的参考价值。

我正在学习ASP.NET CORE,并且正在建立我的第一个Web项目。该项目是关于租车的。我将展示到目前为止对该项目所做的工作以及我遇到的问题。

  1. 我实现了数据模型:1

2。我编写了CarCategory属性,依此类推。

namespace CarRentalSystem.Data.Models
{
    using System.Collections.Generic;

    using CarRentalSystem.Data.Common.Models;

    public class CarCategory : BaseDeletableModel<int>
    {
        public CarCategory()
        {
            this.SmallCars = new HashSet<SmallCarInfo>();
        }

        public string Name { get; set; }

        public string Title { get; set; }

        public string CarDescription { get; set; }

        public string CarImageUrl { get; set; }

        public virtual ICollection<SmallCarInfo> SmallCars { get; set; }
    }
}

3。我的家庭控制器:

namespace CarRentalSystem.Web.Controllers
{
    using System.Diagnostics;
    using System.Linq;

    using CarRentalSystem.Data;
    using CarRentalSystem.Services.Data;
    using CarRentalSystem.Web.ViewModels;
    using CarRentalSystem.Web.ViewModels.Administration.Dashboard;
    using CarRentalSystem.Web.ViewModels.Home;
    using Microsoft.AspNetCore.Mvc;

    public class HomeController : BaseController
    {
        private readonly ICategoriesService categoriesService;

        public HomeController(ICategoriesService categoriesService)
        {
            this.categoriesService = categoriesService;
        }

        public IActionResult Index()
        {
            var viewModel = new IndexViewModels
            {
                Categories = this.categoriesService.GetAll<IndexCategoryViewModel>(),
            };

            // var categories = this.db.CarCategories.Select(x => new IndexCategoryViewModel
            // {
            //    Title = x.Title,
            //    CarDescription = x.CarDescription,
            //    Name = x.Name,
            //    CarImageUrl = x.CarImageUrl,
            // }).ToList();

            // viewModel.Categories = categories;
            return this.View(viewModel);
        }

        public IActionResult Privacy()
        {
            return this.View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return this.View(
                new ErrorViewModel { RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier });
        }
    }
}

4。我在上面写了一些代码。我制作了服务和ViewModels

namespace CarRentalSystem.Web.ViewModels.Home
{
    using CarRentalSystem.Data.Models;
    using CarRentalSystem.Services.Mapping;

    public class IndexCategoryViewModel : IMapFrom<CarCategory>
    {
        public string Title { get; set; }

        public string CarDescription { get; set; }

        public string Name { get; set; }

        public string CarImageUrl { get; set; }

        public string Url => $"/c/{this.Name.Replace(' ', '-')}";
    }
}

namespace CarRentalSystem.Web.ViewModels.Home
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class IndexViewModels
    {
        public IEnumerable<IndexCategoryViewModel> Categories { get; set; }
    }
}

namespace CarRentalSystem.Services.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using CarRentalSystem.Data.Common.Repositories;
    using CarRentalSystem.Data.Models;
    using CarRentalSystem.Services.Mapping;

    public class CategoriesService : ICategoriesService
    {
        private readonly IDeletableEntityRepository<CarCategory> categoriesRepository;

        public CategoriesService(IDeletableEntityRepository<CarCategory> categoriesRepository)
        {
            this.categoriesRepository = categoriesRepository;
        }

        public IEnumerable<T> GetAll<T>(int? count = null)
        {
            IQueryable<CarCategory> query =
                this.categoriesRepository.All();
            if (count.HasValue)
            {
                query = query.Take(count.Value);
            }

            return query.To<T>().ToList();
        }

        public T GetByName<T>(string name)
        {
            var category = this.categoriesRepository.All().Where(x => x.Name == name)
                    .To<T>().FirstOrDefault();

            return category;
        }
    }
}

5。这是我使用的服务,接下来我进行VIEW,整个数据库,也是我所需的thig种子的种子,并且我的主页已准备就绪

namespace CarRentalSystem.Data.Seeding
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using CarRentalSystem.Data.Models;
    using Microsoft.EntityFrameworkCore.Internal;

    public class CategoriesSeeder : ISeeder
    {
        public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.CarCategories.Any())
            {
                return;
            }

            var carCategories = new List<(string Name, string ImageUrl, string CarDescription)>
            {
                ("Small car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/city-car-128.png",
                    "This is a compact car with 2/3 doors. Perfect for couples with small luggage."),
                ("Medium car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/sedan-128.png",
                    "This is medium car with 4/5 doors. Perfect for small families with average luggage."),
                ("Minivan", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/minivan-128.png",
                    "This is a large car with 4/5 doors + extra seats. Perfect for large families with average luggage."),
                ("Minibus", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/van-128.png",
                    "This is a large car with 8+1 seats with big trunk. Perfect for large families or companies with a lot of luggage"),
            };

            foreach (var category in carCategories)
            {
                await dbContext.CarCategories.AddAsync(new CarCategory
                {
                    Name = category.Name,
                    Title = category.Name,
                    CarImageUrl = category.ImageUrl,
                    CarDescription = category.CarDescription,
                });
            }
        }
    }
}

@using CarRentalSystem.Common
@model CarRentalSystem.Web.ViewModels.Home.IndexViewModels
@{
    this.ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome to ElisCar</h1>
</div>

<div class="row">
@foreach (var category in Model.Categories)
{
    <div class="col-md-2 card m-auto" style="width: 18rem;">
        <img src="@category.CarImageUrl" width="100" class="card-img-top" alt="@category.Title">
        <div class="card-body">
            <h5 class="card-title">@category.Title</h5>
            @category.CarDescription
            <a href="@category.Url" class="btn btn-primary">Reservation</a>
        </div>
    </div>
}
</div>

My home page

6。之后,我要从类别中选择汽车,并收到此错误消息3

7。我知道为什么我得到NullReferenceException,因为我没有任何数据,问题是我无法播种它们。

8。我的预订按钮的第二个控制器

namespace CarRentalSystem.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    using CarRentalSystem.Data.Models;
    using CarRentalSystem.Services.Data;
    using CarRentalSystem.Web.ViewModels.Categories;
    using Microsoft.AspNetCore.Mvc;

    public class CategoriesController : Controller
    {
        private readonly ICategoriesService categoriesService;

        public CategoriesController(ICategoriesService categoriesService)
        {
            this.categoriesService = categoriesService;
        }

        public IActionResult ChooseCars(string name)
        {
            var viewModel =
                this.categoriesService.GetByName<CarsViewModel>(name);
            if (viewModel == null)
            {
                return this.NotFound();
            }

            return this.View(viewModel);
        }
    }
}

9.ViewModels

namespace CarRentalSystem.Web.ViewModels.Categories
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    using CarRentalSystem.Data.Models;
    using CarRentalSystem.Services.Mapping;

    public class CarsViewModel : IMapFrom<CarCategory>
    {
        public string Title { get; set; }

        public string Name { get; set; }

        public string CarDescription { get; set; }

        public string CarImageUrl { get; set; }

        public IEnumerable<CarsListViewModel> CarDetails { get; set; }
    }
}

namespace CarRentalSystem.Web.ViewModels.Categories
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    using CarRentalSystem.Data.Models;
    using CarRentalSystem.Services.Mapping;

    public class CarsListViewModel : IMapFrom<SmallCarInfo>
    {
        public string CarModel { get; set; }

        public string CarImage { get; set; }

        public int CarPricePerDay { get; set; }
    }
}
  1. SmallCarsInfo基本模型4

  2. 现在,我正在尝试向数据库中添加其他数据,以添加汽车品牌,价格等:5

12。第二个控制器的视图:

@using CarRentalSystem.Common
@model CarRentalSystem.Web.ViewModels.Categories.CarsViewModel
@{
    this.ViewData["Title"] = "Cars";
}

<h1 class="display-3">Hello!</h1>

<div class="row">
    @foreach (var details in Model.CarDetails)
    {
        <div class="card" style="width: 18rem;">
            <img src="@details.CarImage" class="card-img-top" alt="...">
            <div class="card-body">
                <h5 class="card-title">@details.CarModel</h5>
                <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">@details.CarPricePerDay euro.</li>
                <li class="list-group-item">Dapibus ac facilisis in</li>
                <li class="list-group-item">Vestibulum at eros</li>
            </ul>
            <div class="card-body">
                <a href="#" class="card-link">Card link</a>
                <a href="#" class="card-link">Another link</a>
            </div>
        </div>
    }
</div>

13。现在我将播种机放入启动程序以实现它们:

var seeders = new List<ISeeder>
                          {
                              new RolesSeeder(),
                              new SettingsSeeder(),
                              new CategoriesSeeder(),
                              new SmallCarsSeeder(),
                          };

14。现在,当我启动项目时,出现此错误:7

15。另外,我也没有在SmallCar中将任何数据获取到数据库:8

第一个播种器正在工作,并且主页上的一切都很好,但是当我单击RESERVATION按钮时,我得到了NullReferenceException,然后我将第二个播种器放入了更多数据,但它不起作用,我不知道要怎么做上。

答案

[在我看来,您的SeedAsync方法内部,在foreach循环中将项目添加到数据库上下文之后,您需要调用dbContext.SaveChanges();,它将把所添加的项目“提交”到实际数据库中。否则,您只是将它们添加到内存中跟踪中。试试这个,看看是否有帮助。

以上是关于我无法在第一个ASP.NET CORE APP上播种数据的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Chrome 登录 Dot Net Core 3 ASP.Net App,但可以使用 Firefox

将 ASP.Net Core Web App 项目发送给某人的最佳实践?

ASP.NET Core MVC 会话相同的站点 URL

Windows + IIS 环境部署Asp.Net Core App

Asp.Net Core 入门—— 路由

ASP.NET Core 脚手架在 VS 2017 中不起作用