zoukankan      html  css  js  c++  java
  • EF core的模型映射

    在EF core里,可以通过实现IEntityTypeConfiguration来进行映射。

    一、官网文档

    https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0

    二、示例(.net core控制台程序)

    示例使用的数据库是mysql

    1、新建模型:

        public class Students
        {
            public int Id { get; set; }
    
            public string Name { get; set; }
    
            public decimal Score { get; set; }
        }

    2、实现IEntityTypeConfiguration

        public class StudentsMap : IEntityTypeConfiguration<Students>
        {
            public void Configure(EntityTypeBuilder<Students> builder)
            {
                builder.ToTable("Students");
                builder.HasKey(m => m.Id);
                builder.Property(m => m.Id).ValueGeneratedOnAdd();
                builder.Property(m => m.Name);
            }
        }

    3、定义context

        public class SchoolContext : DbContext
        {
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseMySql("Server=localhost;port=3306;database=test;uid=root;pwd=pwd;Convert Zero Datetime=True;", b => b.MaxBatchSize(30));
            }
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);
                builder.ApplyConfiguration(new StudentsMap());
            }
        }

    4、使用migrations迁移命令,得到数据库。

    5、测试添加数据

        class Program
        {
            static void Main(string[] args)
            {
                using (var _context = new SchoolContext())
                {
                    var stu = new Students()
                    {
                        Name = "test",
                        Score = 100
                    };
                    _context.Set<Students>().Add(stu);
                    _context.SaveChanges();
                }
            }
        }

    6、查看数据库,数据已经插入:

     三、源码

    https://github.com/DavideYang125/efcore_map_demo

  • 相关阅读:
    单步调试及回滚测试
    程序员的自我修养阅读笔记03
    第八周总结
    NABCD项目分析
    程序员的自我修养阅读笔记02
    第七周总结
    程序员的自我修养阅读笔记01
    第六周总结
    结对地铁开发
    第五周总结
  • 原文地址:https://www.cnblogs.com/dayang12525/p/10750559.html
Copyright © 2011-2022 走看看