简体   繁体   English

EF Core - 值不能为空。 (参数'键')

[英]EF Core - Value cannot be null. (Parameter 'key')

I'm having an issue where EF Core does not allow me to add my second migration.我遇到了一个问题,即 EF Core 不允许我添加第二次迁移。 I have the following DataContext setup :我有以下 DataContext 设置:

public class DataContext : IdentityDbContext<User, Role, Guid, IdentityUserClaim<Guid>, UserRole, IdentityUserLogin<Guid>, IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>
{
    public DataContext(DbContextOptions<DataContext> options)
        : base(options)
    {
    }

    /* Global */
    public virtual DbSet<Audit> Audits { get; set; }
    public virtual DbSet<AuditType> AuditType { get; set; }

    /* Portal */
    public virtual DbSet<RefreshToken> RefreshTokens { get; set; }
    public virtual DbSet<Product> Products { get; set; }
    public virtual DbSet<Group> Groups { get; set; }
    public virtual DbSet<GroupType> GroupTypes { get; set; }
    public virtual DbSet<GroupProperty> GroupProperties { get; set; }


    /* SVault */
    public virtual DbSet<LicensePropertyType> LicensePropertyTypes { get; set; }
    public virtual DbSet<LicenseProduct> LicenseProducts { get; set; }
    public virtual DbSet<LicenseState> LicenseStates { get; set; }
    public virtual DbSet<LicenseType> LicenseTypes { get; set; }
    public virtual DbSet<LicenseStatus> LicenseStatus { get; set; }
    public virtual DbSet<BackupState> BackupStates { get; set; }
    public virtual DbSet<BackupMode> BackupModes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        IList<AuditType> audittypes = new List<AuditType>()
        {
            new AuditType() { Id = 1, Name = "USER_CREATE" },
            new AuditType() { Id = 2, Name = "USER_UPDATE" },
            new AuditType() { Id = 3, Name = "USER_DELETE" },
            new AuditType() { Id = 4, Name = "USER_RESET_PASSWORD" },
            new AuditType() { Id = 5, Name = "USER_2FA_GENERATE" },
            new AuditType() { Id = 6, Name = "USER_TOKEN_GENERATE" },
            new AuditType() { Id = 7, Name = "USER_REQUEST_RESET_PASSWORD" },

            new AuditType() { Id = 20, Name = "ROLE_ADD" },
            new AuditType() { Id = 21, Name = "ROLE_DELETE" },

            new AuditType() { Id = 30, Name = "GROUP_CREATE" },
            new AuditType() { Id = 31, Name = "GROUP_UPDATE" },
            new AuditType() { Id = 32, Name = "GROUP_DELETE" },

            new AuditType() { Id = 35, Name = "GROUP_PROPERTY_ADD" },
            new AuditType() { Id = 36, Name = "GROUP_PROPERTY_DELETE" },

            new AuditType() { Id = 50, Name = "SVAULT_LICENSE_CREATE", ProductId = 1 },
            new AuditType() { Id = 51, Name = "SVAULT_LICENSE_UPDATE", ProductId = 1 },
            new AuditType() { Id = 52, Name = "SVAULT_LICENSE_DELETE", ProductId = 1 },
            new AuditType() { Id = 53, Name = "SVAULT_LICENSE_VALIDATE_TRIAL", ProductId = 1 },
            new AuditType() { Id = 54, Name = "SVAULT_LICENSE_MIGRATE", ProductId = 1 },
            new AuditType() { Id = 55, Name = "SVAULT_LICENSE_PROPERTIES_UPDATE", ProductId = 1 },

            new AuditType() { Id = 70, Name = "SVAULT_DATASET_CREATE", ProductId = 1 },
            new AuditType() { Id = 71, Name = "SVAULT_DATASET_UPDATE", ProductId = 1 },
            new AuditType() { Id = 72, Name = "SVAULT_DATASET_DELETE", ProductId = 1 },
            new AuditType() { Id = 73, Name = "SVAULT_DATASET_RESTORE", ProductId = 1 },
            new AuditType() { Id = 74, Name = "SVAULT_DATASET_BACKUP", ProductId = 1 },

            new AuditType() { Id = 80, Name = "SVAULT_DATASET_SCHED_CREATE", ProductId = 1 },
            new AuditType() { Id = 81, Name = "SVAULT_DATASET_SCHED_UPDATE", ProductId = 1 },
            new AuditType() { Id = 82, Name = "SVAULT_DATASET_SCHED_DELETE", ProductId = 1 },
        };

        Guid mProvider = Guid.NewGuid();

        IList<User> users = new List<User>()
        {
            new User() { Id = Guid.NewGuid(), UserName = "*****************", NormalizedUserName = "*****************".ToUpper(), Email = "*****************", NormalizedEmail = "*****************".ToUpper(), EmailConfirmed = true, PasswordHash = "*****************", SecurityStamp = "*****************", ConcurrencyStamp = "*****************", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0, FirstName = "*****************", LastName = "*****************", IsAdmin = true, GroupId = mProvider },
                    new User() { Id = Guid.NewGuid(), UserName = "*****************", NormalizedUserName = "*****************".ToUpper(), Email = "*****************", NormalizedEmail = "*****************".ToUpper(), EmailConfirmed = true, PasswordHash = "*****************", SecurityStamp = "*****************", ConcurrencyStamp = "*****************", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0, FirstName = "*****************", LastName = "*****************", IsAdmin = true, GroupId = mProvider }
        };

        IList<Product> products = new List<Product>()
        {
            new Product(){ Id = 1 ,LongName = "AGS Backup SVault", Description = String.Empty, ShortName = "SVault", RouteUrl = "/svault/dashboard", IconUrl = "assets/images/picto/picto_backup.svg", ThemeColor = "ags-500", Enabled = true },
            new Product(){ Id = 2 ,LongName = "AGS Hosting", Description = String.Empty, ShortName = "Hosting", RouteUrl = "/hosting/dashboard", IconUrl = "assets/images/picto/picto_hosting.svg", ThemeColor = "ags-600", Enabled = false },
            new Product(){ Id = 3 ,LongName = "AGS VEEAM Cloud Connect", Description = String.Empty, ShortName = "VEEAM", RouteUrl = "/veeam/dashboard", IconUrl = "assets/images/picto/picto_veeam.svg", ThemeColor = "ags-300", Enabled = false },
            new Product(){ Id = 4 ,LongName = "AGS Mail Zimbra", Description = String.Empty, ShortName = "Zimbra", RouteUrl = "/mail/dashboard", IconUrl = "assets/images/picto/picto_messagerie.svg", ThemeColor = "ags-700", Enabled = false },
            new Product(){ Id = 5 ,LongName = "AGS Mail Exchange", Description = String.Empty, ShortName = "Exchange", RouteUrl = "/mail/dashboard", IconUrl = "assets/images/picto/picto_messagerie.svg", ThemeColor = "ags-700", Enabled = false },
            new Product(){ Id = 6 ,LongName = "AGS Office365", Description = String.Empty, ShortName = "Office365", RouteUrl = "/office365/dashboard", IconUrl = "assets/images/picto/picto_office.svg", ThemeColor = "ags-800", Enabled = false },
            new Product(){ Id = 7 ,LongName = "AGS MailProtect", Description = String.Empty, ShortName = "MailProtect", RouteUrl = "/mailprotect/dashboard", IconUrl = "assets/images/picto/picto_protect.svg", ThemeColor = "ags-900", Enabled = false },
            new Product(){ Id = 8 ,LongName = "AGS MailInBlack", Description = String.Empty, ShortName = "MailInBlack", RouteUrl = "/mailinblack/dashboard", IconUrl = "assets/images/picto/picto_protect.svg", ThemeColor = "ags-900", Enabled = false },
            new Product(){ Id = 9 ,LongName = "AGS MonCloud", Description = String.Empty, ShortName = "MonCloud", RouteUrl = "/moncloud/dashboard", IconUrl = "assets/images/picto/picto_moncloud.svg", ThemeColor = "ags-400", Enabled = false }
        };
        IList<Role> roles = new List<Role>()
        {
            /* SVault Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 1, Name = RolesHelper.SvaultRoles.RoleAdmin, NormalizedName = RolesHelper.SvaultRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 1, Name = RolesHelper.SvaultRoles.RoleBackup, NormalizedName = RolesHelper.SvaultRoles.RoleBackup.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 1, Name = RolesHelper.SvaultRoles.RoleRestore, NormalizedName = RolesHelper.SvaultRoles.RoleRestore.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 1, Name = RolesHelper.SvaultRoles.RoleRead, NormalizedName = RolesHelper.SvaultRoles.RoleRead.ToUpper() },

            /* Hosting Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 2, Name = RolesHelper.HostingRoles.RoleAdmin, NormalizedName = RolesHelper.HostingRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 2, Name = RolesHelper.HostingRoles.RoleCreate, NormalizedName = RolesHelper.HostingRoles.RoleCreate.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 2, Name = RolesHelper.HostingRoles.RoleDelete, NormalizedName = RolesHelper.HostingRoles.RoleDelete.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 2, Name = RolesHelper.HostingRoles.RoleEdit, NormalizedName = RolesHelper.HostingRoles.RoleEdit.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 2, Name = RolesHelper.HostingRoles.RoleRead, NormalizedName = RolesHelper.HostingRoles.RoleRead.ToUpper() },

            /* VEEAM Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 3, Name = RolesHelper.VEEAMRoles.RoleAdmin, NormalizedName = RolesHelper.VEEAMRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 3, Name = RolesHelper.VEEAMRoles.RoleBackup, NormalizedName = RolesHelper.VEEAMRoles.RoleBackup.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 3, Name = RolesHelper.VEEAMRoles.RoleRestore, NormalizedName = RolesHelper.VEEAMRoles.RoleRestore.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 3, Name = RolesHelper.VEEAMRoles.RoleRead, NormalizedName = RolesHelper.VEEAMRoles.RoleRead.ToUpper() },

            /* Mail Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 4, Name = RolesHelper.MailRoles.RoleAdmin, NormalizedName = RolesHelper.MailRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 4, Name = RolesHelper.MailRoles.RoleCreate, NormalizedName = RolesHelper.MailRoles.RoleCreate.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 4, Name = RolesHelper.MailRoles.RoleDelete, NormalizedName = RolesHelper.MailRoles.RoleDelete.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 4, Name = RolesHelper.MailRoles.RoleEdit, NormalizedName = RolesHelper.MailRoles.RoleEdit.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 4, Name = RolesHelper.MailRoles.RoleRead, NormalizedName = RolesHelper.MailRoles.RoleRead.ToUpper() },

            /* Mail Office */
            new Role() { Id = Guid.NewGuid(), ProductId = 5, Name = RolesHelper.Office365Roles.RoleAdmin, NormalizedName = RolesHelper.Office365Roles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 5, Name = RolesHelper.Office365Roles.RoleCreate, NormalizedName = RolesHelper.Office365Roles.RoleCreate.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 5, Name = RolesHelper.Office365Roles.RoleDelete, NormalizedName = RolesHelper.Office365Roles.RoleDelete.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 5, Name = RolesHelper.Office365Roles.RoleEdit, NormalizedName = RolesHelper.Office365Roles.RoleEdit.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 5, Name = RolesHelper.Office365Roles.RoleRead, NormalizedName = RolesHelper.Office365Roles.RoleRead.ToUpper() },

            /* MailProtect Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 6, Name = RolesHelper.MailProtectRoles.RoleAdmin, NormalizedName = RolesHelper.MailProtectRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 6, Name = RolesHelper.MailProtectRoles.RoleCreate, NormalizedName = RolesHelper.MailProtectRoles.RoleCreate.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 6, Name = RolesHelper.MailProtectRoles.RoleDelete, NormalizedName = RolesHelper.MailProtectRoles.RoleDelete.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 6, Name = RolesHelper.MailProtectRoles.RoleEdit, NormalizedName = RolesHelper.MailProtectRoles.RoleEdit.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 6, Name = RolesHelper.MailProtectRoles.RoleRead, NormalizedName = RolesHelper.MailProtectRoles.RoleRead.ToUpper() },

            /* MonCloud Roles */
            new Role() { Id = Guid.NewGuid(), ProductId = 7, Name = RolesHelper.MonCloudRoles.RoleAdmin, NormalizedName = RolesHelper.MonCloudRoles.RoleAdmin.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 7, Name = RolesHelper.MonCloudRoles.RoleSync, NormalizedName = RolesHelper.MonCloudRoles.RoleSync.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 7, Name = RolesHelper.MonCloudRoles.RoleRestore, NormalizedName = RolesHelper.MonCloudRoles.RoleRestore.ToUpper() },
            new Role() { Id = Guid.NewGuid(), ProductId = 7, Name = RolesHelper.MonCloudRoles.RoleRead, NormalizedName = RolesHelper.MonCloudRoles.RoleRead.ToUpper() },
            };

            IList<GroupType> grouptypes = new List<GroupType>()
            {
                new GroupType() { Id = 1, Name = "Cloud Provider", PictoName = "cloud" },
                new GroupType() { Id = 2, Name = "Partenaire", PictoName = "supervisor_account" },
                new GroupType() { Id = 3, Name = "Client", PictoName = "group" },
                new GroupType() { Id = 4, Name = "Groupe", PictoName = "folder" }
            };

            IList<Group> groups = new List<Group>()
            {
                new Group() { Id = mProvider, Name = "AGS Cloud", GroupTypeId = 1, ParentGroupId = null },
            };

            IList<GroupProperty> groupProperties = new List<GroupProperty>()
            {
                new GroupProperty() { Id = Guid.NewGuid(), ProductId = 1, GroupId = mProvider, Name = Domain.Portal.GroupProperties.community_id.ToString(), Value = Guid.Empty.ToString() }
            };

            IList<LicenseType> licenseTypes = new List<LicenseType>()
            {
                new LicenseType() { Id = 1, Name = "Cloud", IsFilterable = true, OrderBy = 1 },
                new LicenseType() { Id = 2, Name = "Hybrid Mirroir", IsFilterable = true, OrderBy = 2 },
                new LicenseType() { Id = 4, Name = "Hybrid Illimitée", IsFilterable = true, OrderBy = 3 },
                new LicenseType() { Id = 8, Name = "Locale", IsFilterable = true, OrderBy = 4 }
            };

            IList<LicenseStatus> licenseStatus = new List<LicenseStatus>()
            {
                new LicenseStatus() { Id = -1, Name = "NotInstalled", IconName = "highlight_off", IconColor = "grey-600-fg", IsFilterable = true, OrderBy = 3 },
                new LicenseStatus() { Id = 0, Name = "Online", IconName = "wifi", IconColor = "green-600-fg", IsFilterable = true, OrderBy = 1 },
                new LicenseStatus() { Id = 1, Name = "Disabled", IconName = "delete", IconColor = "red-600-fg", IsFilterable = false },
                new LicenseStatus() { Id = 2, Name = "MarkForDelete", IconName = "delete_forever", IconColor = "red-600-fg", IsFilterable = false },
                new LicenseStatus() { Id = 4, Name = "Detached", IconName = "indeterminate_check_box", IconColor = "red-600-fg", IsFilterable = false },
                new LicenseStatus() { Id = 8, Name = "Offline", IconName = "wifi_off", IconColor = "red-600-fg", IsFilterable = true, OrderBy = 2 }
            };

            IList<LicenseState> licenseStates = new List<LicenseState>()
            {
                new LicenseState() { Id = 0, Name = "NotInstalled", IconName = "highlight_off", IconColor = "grey-600-fg", IsFilterable = true, OrderBy = 9 },
                new LicenseState() { Id = 1, Name = "NotConfigured", IconName = "perm_data_setting", IconColor = "grey-600-fg", IsFilterable = true, OrderBy = 8 },
                new LicenseState() { Id = 2, Name = "Failed", IconName = "sms_failed", IconColor = "red-600-fg", IsFilterable = true, OrderBy = 7 },
                new LicenseState() { Id = 3, Name = "NotConnected", IconName = "wifi_off", IconColor = "red-600-fg", IsFilterable = true, OrderBy = 6 },
                new LicenseState() { Id = 4, Name = "Suspended", IconName = "pause", IconColor = "orange-600-fg", IsFilterable = true, OrderBy = 5 },
                new LicenseState() { Id = 5, Name = "Killed", IconName = "stop", IconColor = "orange-600-fg", IsFilterable = true, OrderBy = 4 },
                new LicenseState() { Id = 6, Name = "Maintenance", IconName = "outlined_flag", IconColor = "blue-600-fg", IsFilterable = true, OrderBy = 3 },
                new LicenseState() { Id = 7, Name = "Running", IconName = "play_circle_outline", IconColor = "yellow-600-fg", IsFilterable = true, OrderBy = 2 },
                new LicenseState() { Id = 8, Name = "Completed", IconName = "check", IconColor = "green-600-fg", IsFilterable = true, OrderBy = 1 }
            };

            IList<BackupMode> backupmodes = new List<BackupMode>()
            {
                new BackupMode() { Id = 1, Name = "Cloud", IconName = "cloud", IconColor = "blue-600-fg" },
                new BackupMode() { Id = 2, Name = "Locale", IconName = "dns", IconColor = "grey-600-fg" },
                new BackupMode() { Id = 4, Name = "Cloud & Locale", IconName = "all_inclusive", IconColor = "light-blue-300-fg" }
            };

            /* Code to allow 0 value in BackupState -> Id */
            modelBuilder.Entity<LicenseState>().Property(p => p.Id).ValueGeneratedNever();
            modelBuilder.Entity<BackupState>().Property(p => p.Id).ValueGeneratedNever();
            modelBuilder.Entity<LicenseStatus>().Property(p => p.Id).ValueGeneratedNever();
            /* End */

            modelBuilder.Entity<GroupType>().HasData(grouptypes);
            modelBuilder.Entity<Group>().HasData(groups);
            modelBuilder.Entity<Product>().HasData(products);
            modelBuilder.Entity<Role>().HasData(roles);
            modelBuilder.Entity<User>().HasData(users);
            modelBuilder.Entity<LicenseType>().HasData(licenseTypes);
            modelBuilder.Entity<LicenseStatus>().HasData(licenseStatus);
            modelBuilder.Entity<LicenseState>().HasData(licenseStates);
            modelBuilder.Entity<BackupMode>().HasData(backupmodes);
            modelBuilder.Entity<GroupProperty>().HasData(groupProperties);
            modelBuilder.Entity<AuditType>().HasData(audittypes);

            base.OnModelCreating(modelBuilder);

            /* Has to be set up after base.OnModelCreating */
            modelBuilder.Entity<UserRole>(userRole =>
            {
                userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

                userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });

            modelBuilder.Entity<GroupProperty>().HasIndex(b => b.Name);
            modelBuilder.Entity<GroupProperty>().HasIndex(b => b.Value);

            /*modelBuilder.Entity<Group>().HasOne(b => b.ParentGroup)
                .WithMany(b => b.ChildGroupsHidden)
                .HasForeignKey(b => b.ParentGroupId)
                .OnDelete(DeleteBehavior.Restrict);*/
        }
    }

So when I initially created my first Migration, I used the following:因此,当我最初创建我的第一个迁移时,我使用了以下内容:

Add-Migration "Initialization" -o "Data\\Migrations"

But every time I try to add a second migration, when I'd like to add new field(s) to a table, I get this error saying that Value cannot be null (Parameter: Key)但是每次我尝试添加第二次迁移时,当我想向表中添加新字段时,我都会收到此错误消息,指出Value cannot be null (Parameter: Key)

    public class Audit
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public Guid Id { get; set; }
            public Guid GroupId { get; set; }
            [ForeignKey(nameof(GroupId))]
            public Group Group { get; set; }
            public Guid UserId { get; set; }
            [ForeignKey(nameof(UserId))]
            public User User { get; set; }
            public int AuditTypeId { get; set; }
            [ForeignKey(nameof(AuditTypeId))]
            public AuditType AuditType { get; set; }
            public string IP { get; set; }
            public string BrowserInfo { get; set; }
            public string OriginalObject { get; set; }
            public string UpdatedObject { get; set; }
            public DateTime CreationTime { get; set; }
            **public string TestField { get; set; }**
        }

Does anyone have an idea as to why I'm not able to add that second migration?有没有人知道为什么我不能添加第二次迁移? The error shown is :显示的错误是:

    PM> Add-Migration "Test_Audit"
    Build started...
    Build succeeded.
    Microsoft.EntityFrameworkCore.Infrastructure[10403]
          Entity Framework Core 3.1.2 initialized 'DataContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
    Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (13ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT 1
    Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (12ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
    Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT 1
    Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
    Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT [MigrationId], [ProductVersion]
          FROM [__EFMigrationsHistory]
          ORDER BY [MigrationId];
    Microsoft.EntityFrameworkCore.Migrations[20405]
          No migrations were applied. The database is already up to date.
    Microsoft.EntityFrameworkCore.Infrastructure[10403]
          Entity Framework Core 3.1.2 initialized 'DataContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
    System.ArgumentNullException: Value cannot be null. (Parameter 'key')
       at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
       at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityReferenceMap.TryGet(Object entity, IEntityType entityType, InternalEntityEntry& entry, Boolean throwOnNonUniqueness)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.TryGetEntry(Object entity, IEntityType entityType, Boolean throwOnTypeMismatch)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 containingPrincipalKeys, IReadOnlyList`1 containingForeignKeys, Object oldValue, Object newValue)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.KeyPropertyChanged(InternalEntityEntry entry, IProperty property, IReadOnlyList`1 keys, IReadOnlyList`1 foreignKeys, Object oldValue, Object newValue)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.DetectKeyChange(InternalEntityEntry entry, IProperty property)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ChangeDetector.PropertyChanged(InternalEntityEntry entry, IPropertyBase propertyBase, Boolean setModified)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.PropertyChanged(InternalEntityEntry entry, IPropertyBase property, Boolean setModified)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean isMaterialization, Boolean setModified, Boolean isCascadeDelete, CurrentValueType valueType)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetProperty(IPropertyBase propertyBase, Object value, Boolean isMaterialization, Boolean setModified, Boolean isCascadeDelete)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.CascadeDelete(InternalEntityEntry entry, Boolean force, IEnumerable`1 foreignKeys)
       at Microsoft.EntityFrameworkCore.Update.Internal.UpdateAdapter.CascadeDelete(IUpdateEntry entry, IEnumerable`1 foreignKeys)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDataOperations(DiffContext diffContext)+MoveNext()
       at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IModel source, IModel target)
       at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
       at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
       at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
    Value cannot be null. (Parameter 'key')

My understanding is that somehow we have a Key field which is initialized to null, so it is not able to create the new migration, but I'm not able to find where that problem comes from.我的理解是,不知何故,我们有一个 Key 字段被初始化为 null,因此它无法创建新的迁移,但我无法找到该问题的来源。 The odd part is that the first migration works correctly.奇怪的是第一次迁移工作正常。

Any help would be appreciated, thank you guys!任何帮助将不胜感激,谢谢你们!

Edit from comments从评论中编辑

"...we have to use fixed Guids or fixed Ids. Otherwise, any subsequent migrations will generate that new Guid/Id using the Guid.NewGuid() and try to seed that new data, unfortunately as we have already linked those Ids with some Foreign Key, EF is not able to proceed." “...我们必须使用固定的 Guid 或固定的 Id。否则,任何后续迁移都将使用 Guid.NewGuid() 生成新的 Guid/Id 并尝试播种新数据,不幸的是,因为我们已经将这些 Id 与一些外键,EF 无法继续。”


After you make your initial (or any) migration, be sure to run the Update-Database command to apply your migration.在您进行初始(或任何)迁移后,请务必运行Update-Database命令以应用您的迁移。 After it's been applied fromthe update you can then make a new migration, update, and repeat as needed in youre application development.从更新中应用后,您可以根据应用程序开发的需要进行新的迁移、更新和重复。

for example:例如:

Make changes to ef models, code, etc then run add migration command:对 ef 模型、代码等进行更改,然后运行添加迁移命令:

Add-Migration NewMigrationAfterChanges

Apply the migration with the update db command:使用 update db 命令应用迁移:

Update-Database

Now you can make changes and add a new migration, assuming it updated without an error or something unexpected occurred.现在您可以进行更改并添加新的迁移,假设它已更新且没有错误或发生意外情况。 See MSDN on EF for more details on using EF core.有关使用 EF 核心的更多详细信息,请参阅EF上的MSDN

经过几个小时的研究和@CoderLee 的帮助,我发现我们不应该在播种数据时使用 Guid.NewGuid(),这会导致后续的 Migrations 一次又一次地尝试根据一些外国已经使用的 Guid 来播种数据钥匙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF Core 6 错误“System.ArgumentNullException: Value cannot be null. (Parameter 'key')” using API method POST and PUT - EF Core 6 error "System.ArgumentNullException: Value cannot be null. (Parameter 'key')" using API method POST and PUT Entity Framework Core 和 EF6 - dotnet ef 迁移添加 InitialCreate - 值不能为空。 (参数“连接字符串”) - Entity Framework Core and EF6 - dotnet ef migrations add InitialCreate - Value cannot be null. (Parameter 'connectionString') 值不能为空。 (参数&#39;o&#39;)更新数据库上的EF Core - Value cannot be null. (Parameter 'o') EF Core On Update-Database EF Core 5 检索数据库多对多记录'值不能是 null。 (参数'源')' - EF Core 5 Retrieve database Many-to-Many record 'Value cannot be null. (Parameter 'source')' dotnet ef迁移:值不能为null。 参数名称:contentRootPath - dotnet ef migrations: Value cannot be null. Parameter name: contentRootPath 值不能是 null。 ASP.NET Core 3..0 中的(参数'key') - Value cannot be null. (Parameter 'key') in ASP.NET Core 3..0 无法在 c# 规范流 .net 核心中生成 Allure 报告。 值不能是 null。 (参数'key')值不能是null。 OnScenarioStart(); - Can't get a Allure report to be generated in c# specflow .net Core. Value cannot be null. (Parameter 'key') Value cannot be null. OnScenarioStart(); System.ArgumentNullException:&#39;值不能为null。 参数名称:键 - System.ArgumentNullException: 'Value cannot be null. Parameter name: key' 值不能是 null。 (参数 'key') 关于 Web API POST 方法 - Value cannot be null. (Parameter 'key') On Web API POST Method ArgumentNullException:值不能为null。 参数名称:包含语句上的键 - ArgumentNullException: Value cannot be null. Parameter name: key on Include Statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM