我正在为大学创建一个MVC网站,我正在尝试显示DropCreateDatabase中的数据,我已经使用DbInitialiser输入了字段。我试图使用调试器来解决这个问题,但我无法解决这个问题。
以下是我的DBInitialiser的一部分:
//override
protected override void Seed(ApplicationDbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
// CUSTOMERS
if (!roleManager.RoleExists("Customer"))
{
var role = new IdentityRole();
role.Name = "Customer";
roleManager.Create(role);
string username = "customer1@customer1.com";
string password = "123456";
var user = userManager.FindByName(username);
if (user == null)
{
var newCustomer = new User()
{
FirstName = "Philip",
LastName = "Fry",
Town = "Old New York City",
Role = "Customer",
Email = username,
UserName = username,
EmailConfirmed = true
};
userManager.Create(newCustomer, password);
userManager.AddToRole(newCustomer.Id, "Customer");
}
context.SaveChanges();
//add types of announcements
context.AnnouncementTypes.Add(
new AnnouncementType { TypeName = "Movie Review" }
);
context.SaveChanges();
context.Announcements.Add(
new Announcement
{
//using FirstOrDefault to make sure it doesn't crash if there is 0
//link statement to look for "Movie Review" and return the ProductTypeid
AnnouncementType = context.AnnouncementTypes.FirstOrDefault(a => a.TypeName == "Movie Review"),
AnnouncementTitle = "Back To The Future Part 4",
Description = "A lot better than the 6th one"
}
);
base.Seed(context);
这是被调用的控制器的一部分:
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Announcements
public ActionResult Index()
{
var announcements = db.Announcements.Include(a => a.AnnouncementType);
return View(announcements.ToList());
}
这是观点,问题似乎在这里:
@model IEnumerable<Theatre.Models.Announcement>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.AnnouncementType.TypeName)
</th>
<th>
@Html.DisplayNameFor(model => model.AnnouncementTitle)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AnnouncementType.TypeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.AnnouncementTitle)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AnnouncementId }) |
@Html.ActionLink("Details", "Details", new { id=item.AnnouncementId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AnnouncementId })
</td>
</tr>
}
</table>
foreach循环没有运行,我认为这是因为Model是空的但我不知道如何。我将此代码基于我为大学所做的另一个项目,它可以正常工作。
答案 0 :(得分:0)
看起来你在添加公告后没有调用context.SaveChanges()。