简体   繁体   中英

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. I have the following DataContext setup :

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)

    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. 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."


After you make your initial (or any) migration, be sure to run the Update-Database command to apply your migration. 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:

Add-Migration NewMigrationAfterChanges

Apply the migration with the update db command:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM