.net core EF Core DB First

 

项目 框架 是.net 6.0 所以相关依赖最好是6.0以下的

 nuget 安装

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

 新建一个数据库 TestDBFirst 建立一个表 User

 新建表语句

 1 USE [TestDBFirst]
 2 GO
 3 
 4 /****** Object:  Table [dbo].[User]    Script Date: 2023/4/4 11:33:39 ******/
 5 SET ANSI_NULLS ON
 6 GO
 7 
 8 SET QUOTED_IDENTIFIER ON
 9 GO
10 
11 CREATE TABLE [dbo].[User](
12     [Id] [int] NOT NULL,
13     [Account] [nvarchar](50) NULL,
14     [Password] [nvarchar](50) NULL,
15     [Name] [nvarchar](50) NULL,
16     [Sex] [int] NULL,
17     [Status] [int] NULL,
18  CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED 
19 (
20     [Id] ASC
21 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
22 ) ON [PRIMARY]
23 GO

 此时 可以通过语句 生成 对应的实体

Scaffold-DbContext "server=localhost;database=TestDBFirst;uid=sa;pwd=你的密码;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f

在程序包管理平台执行

 

 结果

1  public partial class User
2     {
3         public int Id { get; set; }
4         public string? Account { get; set; }
5         public string? Password { get; set; }
6         public string? Name { get; set; }
7         public int? Sex { get; set; }
8         public int? Status { get; set; }
9     }

 

 1  public partial class TestDBFirstContext : DbContext
 2     {
 3         public TestDBFirstContext()
 4         {
 5         }
 6 
 7         public TestDBFirstContext(DbContextOptions<TestDBFirstContext> options)
 8             : base(options)
 9         {
10         }
11 
12         public virtual DbSet<User> Users { get; set; } = null!;
13 
14         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
15         {
16             if (!optionsBuilder.IsConfigured)
17             {
18 #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
19                 optionsBuilder.UseSqlServer("server=localhost;database=TestDBFirst;uid=sa;pwd=;");
20             }
21         }
22 
23         protected override void OnModelCreating(ModelBuilder modelBuilder)
24         {
25             modelBuilder.Entity<User>(entity =>
26             {
27                 entity.ToTable("User");
28 
29                 entity.Property(e => e.Id).ValueGeneratedNever();
30 
31                 entity.Property(e => e.Account).HasMaxLength(50);
32 
33                 entity.Property(e => e.Name).HasMaxLength(50);
34 
35                 entity.Property(e => e.Password).HasMaxLength(50);
36             });
37 
38             OnModelCreatingPartial(modelBuilder);
39         }
40 
41         partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
42     }

如果数据库user表出现修改了

修改完就再执行 

Scaffold-DbContext "server=localhost;database=TestDBFirst;uid=sa;pwd=你的密码;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f

 

 如果 从代码 上修改 实体结构可以使用数据迁移来实现

比如我新增 UserId

 

 只需要在程序包管理平台执行 就能得到结果

add-migration init

update-database

 

联合主键的设置 需要通过Fluent API 设置

 1   protected override void OnModelCreating(ModelBuilder modelBuilder)
 2         {
 3             modelBuilder.Entity<User>(entity =>
 4             {
 5                 entity.ToTable("User");
 6                 //联合主键
 7                 entity.HasKey(p => new { p.Id, p.UserId });
 8                 entity.Property(e => e.Id).ValueGeneratedNever();
 9 
10                 entity.Property(e => e.Account).HasMaxLength(50);
11 
12                 entity.Property(e => e.Address).HasMaxLength(50);
13 
14                 entity.Property(e => e.Name).HasMaxLength(50);
15 
16                 entity.Property(e => e.Password).HasMaxLength(50);
17             });
18 
19             OnModelCreatingPartial(modelBuilder);
20         }

通过数据迁移 映射到数据库

add-migration key2

update-database

 

 生成报错

To change the IDENTITY property of a column, the column needs to be dropped and recreated.

这是因为修改了 标识列引起的

需要删除 Migrations 的 init 文件

 

 数据库中的User表也需要删除

然后执行 

add-migration key2

update-database

符合主键已经建立好

 

 

Script-Migration

生成脚本迁移

 

 

这是第二种方式 主要用到  [NotMapped]  特性 其实就是 不让ef 映射这个表,就是将之前的表的删除,然后再创建,这种方式比较优雅

实体框架修改主键

 

.net Entity Framework 

修改主键会提示这玩意,需要删除表,然后重建..

To change the IDENTITY property of a column, the column needs to be dropped and recreated.

对于没有数据的表,可以这样解决...

假设表名为   change_table

首先注释掉 

// modelBuilder.Entity<change_table>();

然后..

[NotMapped]  //  加上这玩意..
[Table("change_table ")]
public partial class change_table {

}

执行命令 

add-migration  删除表change_table 

update-database

然后取消注释,去掉 [NotMapped]  

add-migration  添加表 change_table 

update-database

完事..

对于有主外键引用的.

注释掉 ForeignKey 就可以了..不用注释属性,这样就可以不用改代码了..

对于有数据的表....没啥子想法

 

 

 

  [ConcurrencyCheck] 做并发检查特性

 下面也是做并发检查

[Timestamp]  
public byte[] RowVesion { get; set; }

表名

[Column("Phone")]

 1   public partial class User
 2     {
 3         [Key]
 4         public int Id { get; set; }
 5 
 6         [Key]
 7         public int UserId { get; set; }
 8 
 9         public string? Account { get; set; }
10         public string? Password { get; set; }
11         [ConcurrencyCheck]
12         public string? Name { get; set; }
13         public int? Sex { get; set; }
14         public int? Status { get; set; }
15         public string? Address { get; set; }
16 
17         [Timestamp]
18         public byte[] RowVesion { get; set; }
19     }

 

posted on 2023-04-04 15:35  是水饺不是水饺  阅读(117)  评论(0)    收藏  举报

导航