Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Make access possible to dynamic table LINQ EF6 Code First

The code after the tables here, does generate a new dynamic table in the Database. But, I don't know how to access it or how to add linking to it via C# code.

3NF, three tables.

Tables:

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");
       });
}

The code above here, creates a table like this:

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

EDIT: I am looking at this question now, How to define Many-to-Many relationship through Fluent API Entity Framework?

EDIT, Clarification: Sorry for my delay: This is more related to when, e.g. you already have students or add students separately. But, then want to dynamically, connect them to a course or a number of courses. Similarly, you add new courses. But, these can then be taken by students.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

But, I don't know how to access it or how to add linking to it via C# code.

In EF6 you don't access it directly. Instead just add/remove items to the Student.Courses or Course.Students navigation properties.

EG

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();
            }
        }

    }
}

outputs

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...