【发布时间】:2021-05-02 14:23:29
【问题描述】:
我是 C# 和实体框架的新手,所以我真的很困惑 - 对此深表歉意。
我目前有一个包含两个表的数据库,Artists 和 Albums。
我想在一个页面上显示所有专辑的列表,并将相应的ArtistID(Artist 页面上的外键)链接到它。
我正在尝试将这两个表连接在一起,以便在我的 AllAlbums 页面上呈现它们。
有人可以看看我的代码并指出正确的方向吗?
目前我的页面只渲染出所有专辑,与艺人没有关系。
我将发布我目前拥有的相应代码 sn-ps。
AllAlbum.cshtml.cs
public class AllAlbumModel : PageModel
{
DatabaseContext _Context;
public AllAlbumModel(DatabaseContext databasecontext)
{
_Context = databasecontext;
}
public List<Album> AlbumList { get; set; }
public void OnGet()
{
var data = (from albumlist in _Context.albums
select albumlist).ToList();
AlbumList = data;
}
}
专辑.cs
[Table("albums")]
public class Album
{
[Key]
public int AlbumId {get; set;}
// [Required(ErrorMessage = "Enter Album ID")]
public string Title {get; set;}
// [Required(ErrorMessage = "Enter Title")]
public int ArtistId {get; set;}
}
艺术家.cs
[Table("artists")]
public class Artist
{
[Key]
public int ArtistId {get; set;}
// [Required(ErrorMessage = "Enter Album ID")]
public string Name {get; set;}
// [Required(ErrorMessage = "Enter Title")]
}
DatabaseContext.cs
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Album> albums { get; set; }
public DbSet<Artist> artists { get; set; }
}
AllAlbum.cshtml
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayName("AlbumId")
</th>
<th>
@Html.DisplayName("Title")
</th>
<th>
@Html.DisplayName("ArtistId")
</th>
<th>Edit | Delete</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.AlbumList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.AlbumId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ArtistId)
</td>
<td>
<a asp-page="./AllAlbum" asp-route-id="@item.AlbumId">Edit</a> |
<a asp-page="./AllAlbum" onclick="return confirm('Are you sure you want to delete this album record?');" asp-page-handler="Delete" asp-route-id="@item.AlbumId">Delete</a>
</td>
</tr>
}
</tbody>
【问题讨论】:
-
您的查询只是从专辑表中选择值,而不是“加入”到艺术家表中。见:docs.microsoft.com/en-us/dotnet/csharp/linq/perform-inner-joins
标签: c# entity-framework entity-framework-core