我试着用剃须刀学习asp.net核心,我正在尝试制作一个视频游戏数据库,以跟踪完成的游戏,我还没玩过的游戏等等。
但我有个问题。我有一张桌子Game和一个桌子Developer。因为一个游戏可以有很多开发人员,而一个开发人员可以有很多游戏,所以你做了第三个表DeveloperXGame。他们就像这样
public class Game
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Developer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DeveloperXGame
{
public int DeveloperId { get; set; }
public int JuegoId { get; set; }
public Developer Developer { get; set; }
public Game Game { get; set; }
}
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Game> Game { get; set; }
public DbSet<Developer> Developer { get; set; }
public DbSet<DeveloperXGame> DeveloperXGame { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DeveloperXGame>()
.HasKey(m => new { m.DeveloperId, m.GameId });
}
}我已经为开发人员做了页面,所以我首先手动创建它们。现在我正在尝试创建游戏,我想显示一个选择,在那里我可以选择列表中的一个或多个开发人员(下一步是尝试通过游戏页面添加ajax,如果不存在的话)。但我迷失在这点之上。
我不知道如何加载该列表中的开发人员列表,以及稍后如何在表DeveloperXGame中保存所选项目。
谢谢
发布于 2018-05-04 16:00:20
您可以从上下文中删除public DbSet<DeveloperXGame> DeveloperXGame { get; set; }。
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ApplicationDbContext _context;
public IndexModel(ApplicationDbContext context)
{
_context = context;
}
public Game Game { get; set; }
public IEnumerable<int> Developers { get; set; }
public IEnumerable<SelectListItem> DeveloperList { get; set; }
public IActionResult OnGet()
{
var developers = from m in _context.Developers
select m;
DeveloperList = developers.Select(m => new SelectListItem { Value = m.Id.ToString(), Text = m.Name });
return Page();
}
}以下是视图Index.cshtml
@page
@model RazorPages.TestGame.Pages.Games.IndexModel
@{
ViewData["Title"] = "Index";
}
<div class="row">
<div class="col-md-4">
<form method="post">
<div class="form-group">
<label asp-for="Game.Name" class="control-label"></label>
<input asp-for="Game.Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Developers" class="control-label"></label>
<select asp-for="Developers" asp-items="Model.DeveloperList">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
还可以使用ViewData在视图中传递开发人员列表。您可以像官方文档这里.Hope一样通过这个示例web,它可以帮助您开始工作!
https://stackoverflow.com/questions/50169617
复制相似问题