您好我有一个数据库设置并在.NET应用程序中正常运行。
但是,我无法使用数据库中的内容填充视图。我已经安装了Entity Framework和Framework工具。
任何帮助都会很棒。
这是我的数据库上下文
using Microsoft.EntityFrameworkCore;
namespace _3241_farmDb.Entities
{
public class FarmDbContext : DbContext
{
public FarmDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Farmer> Farmers { get; set; }
public DbSet<Farm> Farms {get; set;}
public DbSet<Child> Children {get; set;}
public DbSet<Attends> Attend {get; set;}
public DbSet<Livestock> Livestocks {get; set;}
public DbSet<Farm_Houses> Farm_Houses {get; set;}
public DbSet<Crops> Crops {get; set;}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Attends>()
.HasKey(c => new { c.FarmerSS, c.HotelID });
modelBuilder.Entity<Child>()
.HasKey(c => new { c.FarmerSS, c.Fname, c.Lname });
}
}
}
这是我的HomeController
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using _3241_farmDb.Entities;
namespace _3241_farmDb.Controllers
{
public class HomeController : Controller
{
private FarmDbContext _context;
public HomeController(FarmDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View(_context.Farmers.AsQueryable()); //CHANGED THIS
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
HomePageViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using _3241_farmDb.Entities;
namespace _3241_farmDb.ViewModel
{
public class HomePageViewModel
{
public string CurrentMessage { get; set; }
public IQueryable<Attends> Attend { get; set; }
public IQueryable<Farmer> Farmers { get; set; }
public IQueryable<Child> Children { get; set; }
public IQueryable<Livestock> Livestock { get; set; }
public IQueryable<Farm_Houses> Farm_Houses { get; set; }
public IQueryable<Crops> Crops { get; set; }
}
}
最后我的index.cshtml查看
@model IQueryable<_3241_farmDb.ViewModel.HomePageViewModel>
@{
ViewBag.Title = "Home";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Welcome to the 3241 Farm Database</h1>
<table>
@foreach (var farmers in Model)
{
<tr>
<td>
<a asp-action="Details" asp-route-id="">@farmers.SS#</a>
</td>
<td>@farmers.Fname</td>
</tr>
}
</table>
<a asp-action="Create">Create</a>
答案 0 :(得分:4)
您需要将实体传递给模型。
public class HomePageViewModel
{
public IList<Farmer> Farmers { get; set; }
public HomePageViewModel()
{
Farmers = new List<Farmer>();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new HomePageViewModel
{
Farmers = _context.Farmers.ToList()
};
return View(model);
}
}
@model _3241_farmDb.ViewModel.HomePageViewModel
<table>
@foreach (var farmers in Model.Farmers)
{
<tr>
<td>
<a asp-action="Details" asp-route-id="">@farmers.SS#</a>
</td>
<td>@farmers.Fname</td>
</tr>
}
</table>