csharp EF6 - 多对多第一种方式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp EF6 - 多对多第一种方式相关的知识,希望对你有一定的参考价值。

namespace EntityFramework.Entity
{
    public class BaseEntity
    {
        public int Id { get; set; }
        public DateTime CreatedTime { get; set; }
        public DateTime ModifiedTime { get; set; }
    }
    
    public class Student : BaseEntity
    {
        public string Name { get; set; }
        public byte Age { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
	
    public class Course : BaseEntity
    {
        public string Name { get; set; }
        public int MaximumStrength { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
}

namespace EntityFramework.Map
{
    public class StudentMap : EntityTypeConfiguration<Student>
    {
        public StudentMap()
        {
            // table
            ToTable("Students");

            // key
            HasKey(t => t.Id);

            // property
            Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(t => t.Name).HasColumnType("VARCHAR").HasMaxLength(50);
            Property(t => t.Age);
            Property(t => t.CreatedTime);
            Property(t => t.ModifiedTime);

            // relationship
            HasMany(t => t.Courses).WithMany(c => c.Students)
                .Map(t => t.ToTable("StudentCourses").MapLeftKey("StudentId").MapRightKey("CourseId"));
        }
    }
	
    public class CourseMap : EntityTypeConfiguration<Course>
    {
        public CourseMap()
        {
            // table
            ToTable("Courses");

            // property
            Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(t => t.Name).HasColumnType("VARCHAR").HasMaxLength(50);
            Property(t => t.MaximumStrength);
            Property(t => t.CreatedTime);
            Property(t => t.ModifiedTime);
        }
    }
}

namespace EntityFramework
{
    public class EfDbContext : DbContext
    {
        public EfDbContext() : base("name=ConnectionString")
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists<EfDbContext>());
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => !string.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType
                                                     && type.BaseType.GetGenericTypeDefinition() ==
                                                     typeof(EntityTypeConfiguration<>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            base.OnModelCreating(modelBuilder);
        }
    }
	
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new EfDbContext())
            {
                ctx.Database.Log = Console.WriteLine;

                var student = new Student
                {
                    Name = "Jeffcky",
                    Age = 26,
                    CreatedTime = DateTime.Now,
                    ModifiedTime = DateTime.Now,
                    Courses = new List<Course>
                    {
                        new Course
                        {
                            Name = "C#",
                            MaximumStrength = 12,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        },
                        new Course
                        {
                            Name = "EntityFramework 6.x",
                            MaximumStrength = 12,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        }
                    }
                };
                Course course = new Course
                {
                    Name = "Web API",
                    MaximumStrength = 12,
                    CreatedTime = DateTime.Now,
                    ModifiedTime = DateTime.Now,
                    Students = new List<Student>
                    {
                        new Student
                        {
                            Name = "Raviendra",
                            Age = 25,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        },
                        new Student
                        {
                            Name = "Pradeep",
                            Age = 25,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        }
                    }
                };
				
                ctx.Students.Add(student);
                ctx.Courses.Add(course);
                ctx.SaveChanges();
            }
            Console.ReadKey();
        }
    }
}

以上是关于csharp EF6 - 多对多第一种方式的主要内容,如果未能解决你的问题,请参考以下文章

EF6 多对多不能删除

如何使用 EF6 更新多对多表

如何使用 EF6 正确设置多对多关系?

创建实体模型多对多 CodeFirst Ef6

数据库表关系:多对多的三中方式

EF Core中的多对多映射如何实现?