c# - 我无法在我的第一个 ASP.NET CORE APP 上播种数据
问题描述
我正在学习 ASP.NET CORE,并且还在构建我的第一个 Web 项目。该项目是关于租车的。我将展示迄今为止对该项目所做的工作以及我的问题是什么。
- 我实现了数据模型: 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.我在上面写了一些代码。我做服务和视图模型
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,整个数据库,也是我需要的东西的播种机,我的主页准备好了
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>
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.视图模型
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; }
}
}
12.第二个控制器的VIEW:
@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.现在我把播种机放到StartUp来实现它们:
var seeders = new List<ISeeder>
{
new RolesSeeder(),
new SettingsSeeder(),
new CategoriesSeeder(),
new SmallCarsSeeder(),
};
14.现在当我开始这个项目时,我得到了这个错误: 7
15.我也没有在 SmallCar 的数据库中获取任何数据: 8
第一个播种机正在工作,主页中的一切都很好,但是当我单击“保留”按钮时,我得到了 NullReferenceException,然后我让第二个播种机获取更多数据并且它不工作,我不知道发生了什么。
解决方案
在我看来,就像在您的SeedAsync
方法内部一样,在foreach
将项目添加到数据库上下文的循环之后,您需要调用dbContext.SaveChanges();
哪个会将添加的项目“提交”到实际数据库中。否则,您只是将它们添加到内存跟踪中。试试这个,看看它是否有帮助。
推荐阅读
- python - 在 gridsearchcv 中正确使用 CV
- google-sheets - 我做了一个计算器,想使用一个按钮将总和存储到另一个单元格以保存单元格
- javascript - 如何使用 contextAPI 在调度中使用等待?
- java - 如何打开默认数字助理设置?
- visual-studio-code - 在 VSCode 中配置工作区 - 需要完整的选项参考
- python - 按屏幕上的任意位置关闭弹出窗口
- python - 使用 spawn 的 Node.js 中的 python 没有响应
- python - 渲染图像时 imshow() 的不同程度是否会导致像素数的变化?
- laravel - 如何解决在 laravel 7 中使用 composer 安装 pusher/pusher-php-server 的问题?
- java - Android recyclerView:如何保留selectableItemBackground以保持该行突出显示?