首页 > 解决方案 > 使访问动态表 LINQ EF6 Code First 成为可能

问题描述

此处表之后的代码确实在数据库中生成了一个新的动态表。但是,我不知道如何访问它或如何通过 C# 代码添加指向它的链接。

3NF,三张桌子。

表:

public class Student
{
    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CourseId { get; set; }
    [Index("CourseName", 2, IsUnique = true)]
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

DBContext.cs

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
       .HasMany<Course>(s => s.Courses)
       .WithMany(c => c.Students)
       .Map(cs =>
       {
           cs.MapLeftKey("FK_StudentID");
           cs.MapRightKey("FK_CourseID");
           cs.ToTable("StudentCourse");
       });
}

上面的代码在这里创建了一个像这样的表:

StudentCourse 
=================================
|  FK_StudentID  | FK_CourseID  |
=================================

编辑:我现在正在看这个问题, 如何通过 Fluent API 实体框架定义多对多关系?

编辑,澄清: 对不起我的延误:这与时间更相关,例如您已经有学生或单独添加学生。但是,然后想要动态地将它们连接到一个课程或多个课程。同样,您添加新课程。但是,这些可以由学生采取。

标签: c#entity-frameworklinq

解决方案


但是,我不知道如何访问它或如何通过 C# 代码添加指向它的链接。

在 EF6 中,您不能直接访问它。相反,只需将项目添加/删除到Student.CoursesCourse.Students导航属性。

例如

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace Ef6Test
{

    public class Student
    {
        [Key, Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public virtual ICollection<Course> Courses { get; } = new HashSet<Course>();
    }

    public class Course
    {
        [Key, Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CourseId { get; set; }
        [Index("CourseName", 2, IsUnique = true)]
        [StringLength(100)]
        public string CourseName { get; set; }

        public virtual ICollection<Student> Students { get; } = new HashSet<Student>();
    }
    public class TestContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
    }

    internal class Program
    {

        public static void Main(string[] args)
        {
            
            using (var db = new TestContext())
            {
                db.Database.Log = m => Console.WriteLine(m);

                if (db.Database.Exists())
                    db.Database.Delete();

                db.Database.Create();

                var s = new Student();
                db.Students.Add(s);
                s.Courses.Add(new Course());
                db.SaveChanges();
            }
        }

    }
}

输出

Started transaction at 1/6/2021 11:52:17 AM -06:00

INSERT [dbo].[Courses]([CourseName])
VALUES (NULL)
SELECT [CourseId]
FROM [dbo].[Courses]
WHERE @@ROWCOUNT > 0 AND [CourseId] = scope_identity()


-- Executing at 1/6/2021 11:52:17 AM -06:00

-- Completed in 9 ms with result: SqlDataReader



INSERT [dbo].[Students]([StudentName], [DateOfBirth])
VALUES (NULL, NULL)
SELECT [StudentID]
FROM [dbo].[Students]
WHERE @@ROWCOUNT > 0 AND [StudentID] = scope_identity()


-- Executing at 1/6/2021 11:52:17 AM -06:00

-- Completed in 7 ms with result: SqlDataReader



INSERT [dbo].[StudentCourses]([Student_StudentID], [Course_CourseId])
VALUES (@0, @1)

-- @0: '1' (Type = Int32)

-- @1: '1' (Type = Int32)

-- Executing at 1/6/2021 11:52:17 AM -06:00

-- Completed in 17 ms with result: 1



Committed transaction at 1/6/2021 11:52:17 AM -06:00

推荐阅读