EF Core中CodeFirst的建库建表

创建项目
1、创建web项目在这里插入图片描述在这里插入图片描述
2添加项目依赖
在这里插入图片描述1、Microsoft.EntityFrameworkCore
这是ef core的核心包

2、Microsoft.EntityFrameworkCore.SqlServer
sqlserver 数据库驱动包

3、Microsoft.EntityFrameworkCore.Tools
工具扩展包

4、Microsoft.EntityFrameworkCore.Proxies
延迟加载实现包

[Table("UserInfo")]
    public class UserInfo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        [MaxLength(50),Required]
        public string name { get; set; }
        [MaxLength(50),Required]
        public string password { get; set; }
    }

Table==>对应数据库表名
Key==>主键
DatabaseGenerated.Identity ==>数据库自动增长列

 public class TestDbContext:DbContext
    {
     	public DbSet<UserInfo> userInfos;
        public TestDbContext(DbContextOptions<TestDbContext> options)
         	:base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            optionsBuilder.UseLazyLoadingProxies(false);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<UserInfo>(entity=> {
                entity.Property(t => t.password).HasDefaultValue("123456");
            });
        }
    }

web项目中找到appsettings.json,在其中添加
"ConnectionStrings": { "dbConnections": "Data Source=172.20.100.232;Initial Catalog=TestDb;User ID=sa;Password=XXX" }
进入在startup.cs中添加引用,
然后配置sqlserver 的连接,告知编译器 需要到程序集 类库中找到 dbContext

   public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<TestDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("dbConnections"),
                p => p.MigrationsAssembly("MyCodeFirstTest.DAL")));
        }

打开nuget 程序包管理控制台:
然后将默认项目设置为刚才dbContext所在的项目
然后输入:Add-Migration Init
然后再输入:update-database Init
这时候,数据库也会初始化好。

接下来看下更新,我们添加一个实体 ,增加一对多的关系

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace MyCodeFirstTest.DAL
{
    [Table("UserInfoDetails")]
    public class UserInfoDetails
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }

        public int userId { get; set; }
        [MaxLength(200),Required]
        public string email { get; set; }

        public virtual UserInfo userinfo { get; set; }


    }
}

修改UserInfo 增加 1对多关系

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace MyCodeFirstTest.DAL
{
    [Table("UserInfo")]
    public class UserInfo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        [MaxLength(50),Required]
        public string name { get; set; }
        [MaxLength(50),Required]
        public string password { get; set; }

        public virtual ICollection<UserInfoDetails> userInfoDetails { get; set; }
    }
}

修改 DbContext。增加 集合和映射关系

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace MyCodeFirstTest.DAL
{
    public class TestDbContext:DbContext
    {
        public DbSet<UserInfo> userInfos;
        public DbSet<UserInfoDetails> infoDetailses { get; set; }
        public TestDbContext(DbContextOptions<TestDbContext> options)
            :base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            optionsBuilder.UseLazyLoadingProxies(false);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder) 
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<UserInfo>().ToTable("UserInfo");

            modelBuilder.Entity<UserInfoDetails>()ToTable("UserInfoDetails");

        }
    }
}

,再次 使用 add-migration “自定义名称” 和 update-database “自定义名称”
刷新数据库

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值