其他分享
首页 > 其他分享> > .NET Core 使用 EF Core 之Code First

.NET Core 使用 EF Core 之Code First

作者:互联网

1.在.NET Core项目中使用Nuget引用包 

Sql Server 请安装 Microsoft.EntityFrameworkCore.SqlServer

 

2.添加实体类

    [Table("AdminUsers")]
    public class AdminUser
    {
        [Key]
        public string Id { get; set; }

        [DisplayName("名称")]
        [MaxLength(30), Required]
        public string Name { get; set; }
        
        [DisplayName("创建日期")]
        public DateTimeOffset Created { get; set; }

        [DisplayName("创建日期")]
        public DateTimeOffset Modified { get; set; }

        public virtual void Create(WFDbContext db)
        {
            Id = Guid.NewGuid().ToString();
            Created = Modified = DateTimeOffset.Now;
        }

        public virtual void Modify(WFDbContext db)
        {
            Modified = DateTimeOffset.Now;
            db.Entry(this).State = EntityState.Modified;
        }
    }
View Code

 

3.添加数据库上下文

    public class WFDbContext : DbContext
    {
        public WFDbContext(DbContextOptions<WFDbContext> options)
            : base(options)
        {
        }
        public DbSet<AdminUser> AdminUsers { get; set; }
        
    }
View Code

 

4.配置EFCore ,在Startup中添加如下代码

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<WFDbContext>(options => options.UseSqlServer("Data Source=.;Initial Catalog=;User ID =;Password =;Integrated Security=True;"));//配置数据库连接字符串
        }

 

5.执行如下命令,默认项目设置为Model所在项目

PM> Add-Migration FirstMigration

出现这个提示,创建Migration成功,但是我的项目未引用Microsoft.EntityFrameworkCore.SqlServer

标签:DateTimeOffset,Core,Code,get,EF,Modified,options,set,public
来源: https://www.cnblogs.com/GoCircle/p/11055913.html