EF中的Guid主键

时间:2021-03-19 13:39:57

 除了自增长ID(int),我们还能把主键设置为GUID类型的。

创建我们的数据表

  CREATE TABLE    dbo.JoinA(
  AGUID UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWSEQUENTIALID() NOT NULL,
  AName NVARCHAR(50) NULL,
  ACode NVARCHAR(50) NULL
  )

实体映射:注解:https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations

[Table("JoinA")]
    public class JoinA
    {
        [Column("AGUID")]
        //需要标识为自增长,不然会给你生成 00000000-0000-0000-0000-000000000000,多条数据就会重复
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }  //主键设置为id
        public string AName { get; set; }
        public string ACode { get; set; }
    }

或者:

  [Table("JoinB")]
    public class JoinB
    {
        [Key]
        [Column("BGUID")]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid BGUID { get; set; }  //如果没有标识为id,需要我们  [Key]  来注解
        public string BName { get; set; }
        public string ACode { get; set; }
    }

上下文:

 public class MyContext : DbContext
    {
        public MyContext()
          : base("name=EFTestEntities")
        {
        }

        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //    //modelBuilder.Entity<JoinA>().Property(x => x.AGUID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        //    //modelBuilder.Entity<JoinB>().Property(x => x.BGUID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        //    base.OnModelCreating(modelBuilder);
        //}

        public virtual DbSet<JoinA> JoinAs { get; set; }
        public virtual DbSet<JoinB> JoinBs { get; set; }
    }

 

测试:

 [HttpGet]
        public async Task<IHttpActionResult> Test()
        {
            List<JoinA> joins = new List<JoinA>
            {
                new JoinA(){ACode="004", AName="测试11" },
                new JoinA(){ACode="004", AName="测试21" },
                new JoinA(){ACode="004", AName="测试31" },
                new JoinA(){ACode="004", AName="测试41" },
                new JoinA(){ACode="004", AName="测试51" },
                new JoinA(){ACode="004", AName="测试61" },
            };
            db.JoinAs.AddRange(joins);          
            await db.SaveChangesAsync();
            return await Task.FromResult(Ok(db.JoinAs));
        }

EF中的Guid主键

 

 Guid效率会比int低一些,但是对于我们的数据迁移是非常好的。

 

Insert一条语句为:

exec sp_executesql N'DECLARE @generated_keys table([AGUID] uniqueidentifier)
INSERT [dbo].[JoinA]([AName], [ACode])
OUTPUT inserted.[AGUID] INTO @generated_keys
VALUES (@0, @1)
SELECT t.[AGUID]
FROM @generated_keys AS g JOIN [dbo].[JoinA] AS t ON g.[AGUID] = t.[AGUID]
WHERE @@ROWCOUNT > 0',N'@0 nvarchar(max) ,@1 nvarchar(max) ',@0=N'dddd',@1=N'ceee'