EF核心-值不能为null。 (参数“键”)

时间:2020-02-26 14:37:11

标签: c# entity-framework .net-core

我遇到了一个问题,即EF Core不允许我添加第二次迁移。 我有以下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);*/
        }
    }

因此,当我最初创建我的第一个迁移时,我使用了以下内容:

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

但是每次我尝试添加第二个迁移时,当我想向表中添加新字段时,都会出现此错误,提示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; }**
        }

有人对我为什么无法添加第二个迁移有任何想法吗? 显示的错误是:

    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')

我的理解是,以某种方式,我们有一个初始化为null的Key字段,因此它无法创建新的迁移,但是我无法找到问题的根源。奇怪的是,第一次迁移可以正常工作。

任何帮助将不胜感激,谢谢大家!

2 个答案:

答案 0 :(得分:1)

根据评论进行编辑

“ ......我们必须使用固定的Guid或固定的ID。否则,任何后续迁移都将使用Guid.NewGuid()生成该新的Guid / Id,并尝试播种该新数据,很遗憾,因为我们已经链接了那些带有某些外键的ID,EF无法继续。”


进行初始(或任何)迁移后,请确保运行Update-Database命令以应用迁移。从更新中应用完之后,您可以根据需要在应用程序开发中进行新的迁移,更新和重复。

例如:

对ef模型,代码等进行更改,然后运行add migration命令:

Add-Migration NewMigrationAfterChanges

使用update db命令应用迁移:

Update-Database

现在,您可以进行更改并添加新的迁移,前提是该迁移已更新且没有错误或发生了意外情况。有关使用EF内核的更多详细信息,请参见MSDN on EF

答案 1 :(得分:1)

在@CoderLee经过数小时的研究和帮助之后,我发现在播种数据时不应使用Guid.NewGuid(),这将导致后续的迁移根据已使用的Guid一次又一次地尝试播种数据。通过某些外键。