在 EF Core ASP.NET Core Razor Pages .NET6 中插入自动生成的桥 table
Insert to autogenerated Bridge table in EF Core ASP.NET Core Razor Pages .NET6
我是 EF 的新手,需要帮助来理解以下内容:
我在数据库中有一个 Class table 和一个学生 table。一个 Class 可以有很多学生,一个学生可以在很多 class 中。我有一个由 EF 核心自动生成的 table,名为 ClassModelStudent。它有以下字段:
我创建了一个 razor 页面来创建 class 并且在 post 事件中,按钮应该发送 ClassID 并重定向到 AddStudents 页面。
以下是 AddStudents Class 的代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using TestProject.Model;
namespace TestProject.Pages.Classes
{
public class EnrollmentModel : PageModel
{
private readonly TestProject.Data.TestProjectContext _context;
public EnrollmentModel(TestProject.Data.TestProjectContext context)
{
_context = context;
}
[BindProperty]
public Enrollment Enrollments { get; set; }
public SelectList Classes { get; set; }
public IList<Student> UserProfile { get; set; }
[BindProperty(SupportsGet = true)]
public string? SearchString { get; set; }
public async Task OnGetAsync()
{
var students = from s in _context.User_Profile
select s;
if (!string.IsNullOrEmpty(SearchString))
{
students = students.Where(s => s.FirstName.Contains(SearchString));
}
UserProfile = await students.ToListAsync();
var classes = from i in _context.Class
orderby i.Description
select i;
Classes = new SelectList(classes, "ClassID",
"Description");
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//THIS IS WHERE I TRIED ACCESSING CLASSMODELSTUDENT TABLE
//AND THE CONTEXT DID NOT SEE IT
// _context.e
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
我目前已将其连接到注册 table。我什至不确定是否应该将其写入自动生成的 table ClassModelStudents 或手动创建的注册?
注册 table 如下所示:
在 AddStudents 页面中,我显示了 table 中的学生列表。我在 table 的每一行中创建了 'Add To Class' 按钮。我想在单击 'add to class' 按钮时将该学生添加到选定的 class。我应该写信给 ClassModelStudents table。
请看下面的AddStudents页面截图:
我不明白的是如何为 ClassModelStudent 创建 class(模型)?因为我无法使用上下文直接访问此 table。如何访问此 table 以将 ClassID 和 StudentID 写入其中?
请指教..
非常感谢您的帮助..
以下是我的模型 class for ClassModel:
public class ClassModel
{
[Key]
[Required]
[Display(Name ="Class ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClassID { get; set; }
//[ForeignKey("UserProfile")]
//[Display(Name = "User ID")]
//public virtual int ID { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int Occurence { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Startdate { get; set; }
[Required]
[DataType(DataType.Time)]
public DateTime From { get; set; }
[Required]
[DataType(DataType.Time)]
//[GreaterThanOrEqualTo("From")]
public DateTime To { get; set; }
[Required]
[DataType(DataType.Currency)]
public double Fees { get; set; }
[DisplayFormat(NullDisplayText = "No Instructor Assigned")]
[ForeignKey("InstructorID")]
public virtual int InstructorID { get; set; }
public Instructor? Instructor { get; set; }
[DisplayFormat(NullDisplayText = "No Student Assigned")]
public ICollection<Student>? Students { get; set; }
public ICollection<Enrollment>? Enrollment { get; set; }
}
这是注册 class 型号:
public class Enrollment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EnrollmentID { get; set; }
[Required]
[ForeignKey("ClassID")]
public virtual int ClassID { get; set; }
[Required]
[ForeignKey("StudentID")]
public virtual int StudentID { get; set; }
[Required]
public ClassModel? Class { get; set; }
[Required]
public Student? Student { get; set; }
}
以下是学生模型:
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "StudentID")]
public int StudentID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public Boolean Status { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[Phone]
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
public string EmergencyContactName { get; set; }
[Phone]
[DataType(DataType.PhoneNumber)]
public string EmergencyContactNumber { get; set; }
[Required]
public string Gender { get; set; }
public string FullName
{
get { return LastName + ", " + FirstName; }
}
[DisplayFormat(NullDisplayText = "No Class Assigned")]
public ICollection<ClassModel>? Classes { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
我没有 ClassModelStudent 的代码,因为它是自动生成的。
当你在 TestProjectContext
中创建 many-to-many
关系时,你是否像这样编写代码:
.......
public Dbset<Class> classes;
public Dbset<students> students;
ClassModelStudent
table是EF core自动生成的,所以不能用_context.ClassModelStudent
插入任何数据?
如果你的问题像我上面提到的那样,你可以使用另一种方法来创建many-to-many
关系,我写了一个简单的演示:
型号
public class Group
{
public int Id { get; set; }
public string GroupName { get; set; }
public List<GroupMembers> GroupMembers { get; set; }
}
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public List<GroupMembers> GroupMembers { get; set; }
}
public class GroupMembers
{
public int Id { get; set; }
public int UserId { get; set; }
public User user { get; set; }
public int GroupId { get; set; }
public Group group { get; set; }
}
DataContext
public class WebTestContext : DbContext
{
public WebTestContext(DbContextOptions<WebTestContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<GroupMembers>()
.HasKey(gm => new { gm.UserId, gm.GroupId });
modelBuilder.Entity<GroupMembers>()
.HasOne(gm => gm.group)
.WithMany(group=> group.GroupMembers)
.HasForeignKey(gm => gm.GroupId);
modelBuilder.Entity<GroupMembers>()
.HasOne(gm => gm.user)
.WithMany(user => user.GroupMembers)
.HasForeignKey(gm => gm.UserId);
}
public DbSet<User> usertable { get; set; }
public DbSet<Group> grouptable { get; set; }
public DbSet<GroupMembers> GroupMembers { get; set; }
}
通过这种方式在 DataContext 中创建多对多关系,您可以在 pagemodel 中使用 _context.(Relational tables)
。
============================================= ==============
如果Enrollment
table是ClassModel
和Student
的Relational table,则不需要让EF core创建其他关系table.
型号
public class ClassModel
{
[Key]
public int ClassID { get; set; }
public string Description { get; set; }
public string ClassName { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
public class Enrollment
{
[Key]
public int EnrollmentID { get; set; }
[ForeignKey("ClassID")]
public virtual int ClassID { get; set; }
[Required]
[ForeignKey("StudentID")]
public virtual int StudentID { get; set; }
[Required]
public ClassModel? Class { get; set; }
[Required]
public Student? Student { get; set; }
}
public class Student
{
[Key]
public int StudentID { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
TestProjectContext
public class TestProjectContext : DbContext
{
public TestProjectContext(DbContextOptions<TestProjectContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enrollment>()
.HasKey(gm => new { gm.ClassID, gm.StudentID });
modelBuilder.Entity<Enrollment>()
.HasOne(gm => gm.Class)
.WithMany(group => group.Enrollments)
.HasForeignKey(gm => gm.ClassID);
modelBuilder.Entity<Enrollment>()
.HasOne(gm => gm.Student)
.WithMany(user => user.Enrollments)
.HasForeignKey(gm => gm.StudentID);
}
public DbSet<ClassModel> ClassModels { get; set; }
public DbSet<Student> students { get; set; }
public DbSet<Enrollment> enrollments { get; set; }
}
那么,你只有三个tables
您可以在 PageModel 中使用它们中的任何一个
我是 EF 的新手,需要帮助来理解以下内容: 我在数据库中有一个 Class table 和一个学生 table。一个 Class 可以有很多学生,一个学生可以在很多 class 中。我有一个由 EF 核心自动生成的 table,名为 ClassModelStudent。它有以下字段:
我创建了一个 razor 页面来创建 class 并且在 post 事件中,按钮应该发送 ClassID 并重定向到 AddStudents 页面。
以下是 AddStudents Class 的代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using TestProject.Model;
namespace TestProject.Pages.Classes
{
public class EnrollmentModel : PageModel
{
private readonly TestProject.Data.TestProjectContext _context;
public EnrollmentModel(TestProject.Data.TestProjectContext context)
{
_context = context;
}
[BindProperty]
public Enrollment Enrollments { get; set; }
public SelectList Classes { get; set; }
public IList<Student> UserProfile { get; set; }
[BindProperty(SupportsGet = true)]
public string? SearchString { get; set; }
public async Task OnGetAsync()
{
var students = from s in _context.User_Profile
select s;
if (!string.IsNullOrEmpty(SearchString))
{
students = students.Where(s => s.FirstName.Contains(SearchString));
}
UserProfile = await students.ToListAsync();
var classes = from i in _context.Class
orderby i.Description
select i;
Classes = new SelectList(classes, "ClassID",
"Description");
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//THIS IS WHERE I TRIED ACCESSING CLASSMODELSTUDENT TABLE
//AND THE CONTEXT DID NOT SEE IT
// _context.e
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
我目前已将其连接到注册 table。我什至不确定是否应该将其写入自动生成的 table ClassModelStudents 或手动创建的注册? 注册 table 如下所示:
在 AddStudents 页面中,我显示了 table 中的学生列表。我在 table 的每一行中创建了 'Add To Class' 按钮。我想在单击 'add to class' 按钮时将该学生添加到选定的 class。我应该写信给 ClassModelStudents table。
请看下面的AddStudents页面截图:
我不明白的是如何为 ClassModelStudent 创建 class(模型)?因为我无法使用上下文直接访问此 table。如何访问此 table 以将 ClassID 和 StudentID 写入其中?
请指教.. 非常感谢您的帮助..
以下是我的模型 class for ClassModel:
public class ClassModel
{
[Key]
[Required]
[Display(Name ="Class ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClassID { get; set; }
//[ForeignKey("UserProfile")]
//[Display(Name = "User ID")]
//public virtual int ID { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int Occurence { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Startdate { get; set; }
[Required]
[DataType(DataType.Time)]
public DateTime From { get; set; }
[Required]
[DataType(DataType.Time)]
//[GreaterThanOrEqualTo("From")]
public DateTime To { get; set; }
[Required]
[DataType(DataType.Currency)]
public double Fees { get; set; }
[DisplayFormat(NullDisplayText = "No Instructor Assigned")]
[ForeignKey("InstructorID")]
public virtual int InstructorID { get; set; }
public Instructor? Instructor { get; set; }
[DisplayFormat(NullDisplayText = "No Student Assigned")]
public ICollection<Student>? Students { get; set; }
public ICollection<Enrollment>? Enrollment { get; set; }
}
这是注册 class 型号:
public class Enrollment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EnrollmentID { get; set; }
[Required]
[ForeignKey("ClassID")]
public virtual int ClassID { get; set; }
[Required]
[ForeignKey("StudentID")]
public virtual int StudentID { get; set; }
[Required]
public ClassModel? Class { get; set; }
[Required]
public Student? Student { get; set; }
}
以下是学生模型:
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "StudentID")]
public int StudentID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public Boolean Status { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[Phone]
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
public string EmergencyContactName { get; set; }
[Phone]
[DataType(DataType.PhoneNumber)]
public string EmergencyContactNumber { get; set; }
[Required]
public string Gender { get; set; }
public string FullName
{
get { return LastName + ", " + FirstName; }
}
[DisplayFormat(NullDisplayText = "No Class Assigned")]
public ICollection<ClassModel>? Classes { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
我没有 ClassModelStudent 的代码,因为它是自动生成的。
当你在 TestProjectContext
中创建 many-to-many
关系时,你是否像这样编写代码:
.......
public Dbset<Class> classes;
public Dbset<students> students;
ClassModelStudent
table是EF core自动生成的,所以不能用_context.ClassModelStudent
插入任何数据?
如果你的问题像我上面提到的那样,你可以使用另一种方法来创建many-to-many
关系,我写了一个简单的演示:
型号
public class Group
{
public int Id { get; set; }
public string GroupName { get; set; }
public List<GroupMembers> GroupMembers { get; set; }
}
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public List<GroupMembers> GroupMembers { get; set; }
}
public class GroupMembers
{
public int Id { get; set; }
public int UserId { get; set; }
public User user { get; set; }
public int GroupId { get; set; }
public Group group { get; set; }
}
DataContext
public class WebTestContext : DbContext
{
public WebTestContext(DbContextOptions<WebTestContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<GroupMembers>()
.HasKey(gm => new { gm.UserId, gm.GroupId });
modelBuilder.Entity<GroupMembers>()
.HasOne(gm => gm.group)
.WithMany(group=> group.GroupMembers)
.HasForeignKey(gm => gm.GroupId);
modelBuilder.Entity<GroupMembers>()
.HasOne(gm => gm.user)
.WithMany(user => user.GroupMembers)
.HasForeignKey(gm => gm.UserId);
}
public DbSet<User> usertable { get; set; }
public DbSet<Group> grouptable { get; set; }
public DbSet<GroupMembers> GroupMembers { get; set; }
}
通过这种方式在 DataContext 中创建多对多关系,您可以在 pagemodel 中使用 _context.(Relational tables)
。
============================================= ==============
如果Enrollment
table是ClassModel
和Student
的Relational table,则不需要让EF core创建其他关系table.
型号
public class ClassModel
{
[Key]
public int ClassID { get; set; }
public string Description { get; set; }
public string ClassName { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
public class Enrollment
{
[Key]
public int EnrollmentID { get; set; }
[ForeignKey("ClassID")]
public virtual int ClassID { get; set; }
[Required]
[ForeignKey("StudentID")]
public virtual int StudentID { get; set; }
[Required]
public ClassModel? Class { get; set; }
[Required]
public Student? Student { get; set; }
}
public class Student
{
[Key]
public int StudentID { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public ICollection<Enrollment>? Enrollments { get; set; }
}
TestProjectContext
public class TestProjectContext : DbContext
{
public TestProjectContext(DbContextOptions<TestProjectContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enrollment>()
.HasKey(gm => new { gm.ClassID, gm.StudentID });
modelBuilder.Entity<Enrollment>()
.HasOne(gm => gm.Class)
.WithMany(group => group.Enrollments)
.HasForeignKey(gm => gm.ClassID);
modelBuilder.Entity<Enrollment>()
.HasOne(gm => gm.Student)
.WithMany(user => user.Enrollments)
.HasForeignKey(gm => gm.StudentID);
}
public DbSet<ClassModel> ClassModels { get; set; }
public DbSet<Student> students { get; set; }
public DbSet<Enrollment> enrollments { get; set; }
}
那么,你只有三个tables
您可以在 PageModel 中使用它们中的任何一个