【发布时间】:2021-06-19 16:05:28
【问题描述】:
我试图呈现一对多的关系,但总是出现错误,我无法继续前进。 如果有人能找出错误,非常感谢。 最终目标是在 Villas 表中选择一条记录,并能够关联另一个表中的记录。 谢谢
using Microsoft.EntityFrameworkCore;
namespace LeisureVillas.RazorPages.Models
{
public class VillaStatAContext : DbContext
{
public DbSet<StatementA> Tbl_Statement_Autos { get; set; }
public DbSet<Villa> Tbl_Villas { get; set; }
public VillaStatAContext(DbContextOptions<VillaStatAContext> options) : base(options)
{
}
#region Required
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Villa>()
.HasMany<StatementA>(s => s.StatementAs)
.WithOne(p => p.Villas)
.HasForeignKey(s => s.Stat_A_Villas);
#endregion
}
}
}
using LeisureVillas.RazorPages.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.Linq;
namespace LeisureVillas.RazorPages.Pages
{
[Authorize(Roles = "Manager")]
public class VillaStatementA : PageModel
{
private readonly VillaStatAContext db = null;
public List<Villa> Villas { get; set; }
public List<StatementA> StatementAs { get; set; }
public void OnGet()
{
this.Villas = (from e in db.Tbl_Villas orderby e.Vill_Name select e).ToList();
}
}
}
【问题讨论】:
-
有什么错误?
-
此时它出现错误,因为我设置了 db = null 并且我不能从这里开始
-
我打算把两张表的关系放到cshtml页面
-
如果你这样做,它不会为空:
db = new VillaStatAContext() -
您可能希望使用依赖注入来提供
VillaStatAContext作为页面模型构造函数。
标签: c# entity-framework asp.net-core entity-relationship razor-pages