【问题标题】:Entity Framework Code First will not set Identity to YesEntity Framework Code First 不会将 Identity 设置为 Yes
【发布时间】:2017-03-02 16:18:08
【问题描述】:

我有 Code First 实现的类,我试图让它创建表,以便将 Id 字段设置为 Identity = yes。不管我做什么,虽然它似乎总是设置为否。

我尝试在 Id 属性上添加 .HasKey 和 HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity),如下所示:

 public class ApplicationDbContext : IdentityDbContext<User, Role, Guid, UserLogin, UserRole, UserClaim>
 {
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.HasDefaultSchema("dbo");

                      modelBuilder.Entity<User>().Map(c =>
        {
            c.ToTable("User");
            c.Property(p => p.Id).HasColumnName("UserId");                
            c.Properties(p => new
            {
                p.AccessFailedCount,
                p.Email,
                p.EmailConfirmed,
                p.PasswordHash,
                p.PhoneNumber,
                p.PhoneNumberConfirmed,
                p.TwoFactorEnabled,
                p.SecurityStamp,
                p.LockoutEnabled,
                p.LockoutEndDateUtc,
                p.UserName,
                p.FirstName,
                p.MiddleName,
                p.LastName,
                p.IsActive,
                p.LastLogin,
                p.CreatedBy,
                p.CreatedOn,
                p.LastModifiedBy,
                p.LastModifiedOn
            });
        }).HasKey(c => c.Id);
        modelBuilder.Entity<User>().HasMany(c => c.Logins).WithOptional().HasForeignKey(c => c.UserId);
        modelBuilder.Entity<User>().HasMany(c => c.Claims).WithOptional().HasForeignKey(c => c.UserId);
        modelBuilder.Entity<User>().HasMany(c => c.Roles).WithRequired().HasForeignKey(c => c.UserId);
        modelBuilder.Entity<User>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Entity<User>().HasKey(p => p.Id);

我还将类中 Id 属性的 Attribute 设置为 Identity

    public class User : IdentityUser<Guid, UserLogin, UserRole, UserClaim>, IEntity
    {
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, Guid> manager, string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override Guid Id { get; set; }
    [MaxLength(256)]
    public string FirstName { get; set; }
    [MaxLength(256)]
    public string MiddleName { get; set; }
    [MaxLength(256)]
    public string LastName { get; set; }
    public bool IsActive { get; set; }
    public DateTime? LastLogin { get; set; }
    public Guid? CreatedBy { get; set; }
    public DateTime? CreatedOn { get; set; }
    public Guid? LastModifiedBy { get; set; }
    public DateTime? LastModifiedOn { get; set; }         
}
}

实际Migration中的Up()方法如下:

CreateTable(
            "dbo.User",
            c => new
                {
                    **UserId = c.Guid(nullable: false, identity: true),**
                    FirstName = c.String(maxLength: 256),
                    MiddleName = c.String(maxLength: 256),
                    LastName = c.String(maxLength: 256),
                    IsActive = c.Boolean(nullable: false),
                    LastLogin = c.DateTime(),
                    CreatedBy = c.Guid(),
                    CreatedOn = c.DateTime(),
                    LastModifiedBy = c.Guid(),
                    LastModifiedOn = c.DateTime(),
                    Email = c.String(),
                    EmailConfirmed = c.Boolean(nullable: false),
                    PasswordHash = c.String(),
                    SecurityStamp = c.String(),
                    PhoneNumber = c.String(),
                    PhoneNumberConfirmed = c.Boolean(nullable: false),
                    TwoFactorEnabled = c.Boolean(nullable: false),
                    LockoutEndDateUtc = c.DateTime(),
                    LockoutEnabled = c.Boolean(nullable: false),
                    AccessFailedCount = c.Int(nullable: false),
                    UserName = c.String(),
                })
            .PrimaryKey(t => t.UserId);

正如您所看到的,当脚本运行时,身份设置为否。

【问题讨论】:

    标签: c# sql-server entity-framework


    【解决方案1】:

    【讨论】:

    • 我应该知道的!我一直高度关注错误的事情。我真正需要做的就是将 DefaultValue 设置为 newid()。我刚从带有 BIGINT 主键的表切换过来,我的大脑还在设置身份......男孩,我现在觉得自己很愚蠢。
    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多