You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 7迁移触发NullReferenceException问题排查求助

EF Core 7.0.5 Code First创建迁移时抛出NullReferenceException

环境信息

  • IDE:VS2022
  • ORM:EF Core 7.0.5
  • 数据库:LocalDB
  • 开发模式:Code First

执行命令 dotnet ef migrations add Test 时,编译成功但抛出NullReferenceException,报错堆栈如下:

Build started...
Build succeeded.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Initialize(ColumnOperation columnOperation, IColumn column, RelationalTypeMapping typeMapping, Boolean isNullable, IEnumerable`1 migrationsAnnotations, Boolean inline)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.InitializeColumnHelper(ColumnOperation columnOperation, IColumn column, Boolean inline)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Add(IColumn target, DiffContext diffContext, Boolean inline)+MoveNext()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.CastIterator[TResult](IEnumerable source)+MoveNext()
   at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Add(ITable target, DiffContext diffContext)+MoveNext()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffCollection[T](IEnumerable`1 sources, IEnumerable`1 targets, DiffContext diffContext, Func`4 diff, Func`3 add, Func`3 remove, Func`4[] predicates)+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(IRelationalModel source, IRelationalModel 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, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   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)
Object reference not set to an instance of an object.

相关代码

CDbContext

using E_Sporg.Domain.DomainModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace E_Sporg.Persistenc
{
    public class CDbContext : DbContext
    {
        #region fields
        public DbSet<Player> players => Set<Player>();
        public DbSet<Team> teams => Set<Team>();
        public DbSet<League> leagues => Set<League>();
        public DbSet<Matches> matches => Set<Matches>();
        public DbSet<MatchStatsLeague> matchstatsleague => Set<MatchStatsLeague>();
        #endregion

        #region ctor
        public CDbContext(DbContextOptions<CDbContext> options) : base(options) { }
        #endregion

        #region methods
        public bool SaveAllChanges()
        {
            var records = SaveChanges();
            return records > 0;
        }
        #endregion
    }
}

Player实体

namespace E_Sporg.Domain.DomainModel
{
    public class Player
    {
        #region properties
        public Guid Id { get; set; } = Guid.Empty;
        public string PlayerName { get; set; }  = string.Empty;
        public Team _team { get; set; } = default!;
        public Guid TeamId { get; set; } = Guid.Empty;
        #endregion

        #region ctor
        public Player(): base() { Id = Guid.NewGuid(); }
        #endregion

        #region methods
        public Player Set(Guid id, string playerName, Team _team)
        {
            Id = (id == Guid.Empty) ? Guid.NewGuid() : id;
            PlayerName = playerName;
            TeamId = _team.Id;
            return this;
        }
        #endregion
    }
}

Team实体

namespace E_Sporg.Domain.DomainModel
{
    public class Team 
    {
        #region properties
        public Guid Id { get; set; } = Guid.Empty;
        public string _teamName { get; set; } = string.Empty;
        [NotMapped] public Dictionary<Guid, Player> _player { get; set; } = default!;
        public Guid LeagueId { get; set; } = Guid.Empty;
        #endregion

        #region ctor
        public Team(): base() { Id = Guid.NewGuid(); }
        #endregion

        #region methods
        public Team Set(Guid id, string teamName, Guid leagueid)
        {
            Id = (id == Guid.Empty) ? Guid.NewGuid() : id;
            _teamName = teamName;
            LeagueId = leagueid;
            return this;
        }
        #endregion
    }
}

League实体

namespace E_Sporg.Domain.DomainModel
{
    public class League
    {
        #region properties
        public Guid Id { get; set; } = Guid.Empty;
        public string LeagueName { get; set; } = string.Empty;
        [NotMapped] public Dictionary<Guid, Team> _teams { get; set; } = default!;
        [NotMapped] public Dictionary<Guid, Matches> _matches { get; set; } = default!;
        #endregion

        #region ctor
        public League() : base() { Id = Guid.NewGuid(); }
        #endregion

        #region methods
        public League Set(Guid id, string leagueName)
        {
            Id = (id == Guid.Empty) ? Guid.NewGuid() : id;
            LeagueName = leagueName;
            return this;
        }

        public void AddTeam(Team team)
        {
            if (!_teams.ContainsKey(team.Id))
            {
                _teams.Add(team.Id, team);
                return;
            }
            else return;
        }

        public void RemoveTeam(Team team)
        {
            if (_teams.ContainsKey(team.Id))
            {
                _teams.Remove(team.Id);
                return;
            }
            else return;
        }

        public void AddMatch(Matches match)
        {
            if (!_matches.ContainsKey(match.Id))
            {
                _matches.Add(match.Id, match);
                return;
            }
            else return;
        }

        public void RemoveMatch(Guid matchId)
        {
            if (_matches.ContainsKey(matchId))
            {
                _matches.Remove(matchId);
                return;
            }
            else return;
        }
        #endregion
    }
}

Matches实体

namespace E_Sporg.Domain.DomainModel
{
    public class Matches
    {
        #region properties
        public Guid Id { get; set; } = Guid.Empty;
        public Team TeamBlue { get; set; } = default!;
        public Guid TeamBlueID { get; set; } = Guid.Empty;
        public Team TeamRed { get; set; } = default!;
        public Guid TeamRedID { get; set; } =Guid.Empty;
        [NotMapped] public Dictionary<Guid, object[]> TeamBlueStats { get; set; } = default!;
        [NotMapped] public Dictionary<Guid, object[]> TeamRedStats { get; set; } = default!;
        #endregion

        #region ctor
        public Matches(): base() { Id = Guid.NewGuid(); }
        #endregion

        #region methods
        public Matches Set(Guid id, Team _teamBlue, Team _teamRed)
        {
            Id = (id ==  Guid.Empty) ? Guid.NewGuid() : id;
            TeamBlue = _teamBlue;
            TeamBlueID = TeamBlue.Id;
            TeamRed = _teamRed;
            TeamRedID = TeamRed.Id;
            return this;
        }
        #endregion
    }
}

MatchStatsLeague实体

namespace E_Sporg.Domain.DomainModel
{
    public class MatchStatsLeague
    {
        #region properties
        public Guid Id { get; set; } = Guid.Empty;
        public Guid LeagueId { get; set; } = Guid.Empty;
        public Guid MatchId { get; set; } = Guid.Empty;
        public Guid PlayerId { get; set; } = Guid.Empty;
        //stats
        public string Champion { get; set; } = string.Empty;
        public Role Role { get; set; }
        public int Kills { get; set; } = int.MinValue;
        public int Deaths { get; set; } = int.MinValue;
        public int Assists { get; set; } = int.MinValue;
        public int DmgPerMin { get; set; } = int.MinValue;
        public int CSPerMin { get; set; } = int.MinValue;
        public int GoldPerMin { get; set; } = int.MinValue;
        #endregion

        #region ctor
        public MatchStatsLeague() : base() { Id = Guid.NewGuid(); }
        #endregion

        public MatchStatsLeague Set(Guid _leagueId, Guid _matchId, Guid _playerId, object[] _playerStats)
        {
            
            LeagueId = _leagueId;
            MatchId = _matchId;
            PlayerId = _playerId;
           
            Champion = (string)_playerStats[0];
            Role = (Role)_playerStats[1];
            Kills = (int)_playerStats[2];
            Deaths = (int)_playerStats[3];
            Assists = (int)_playerStats[4];
            DmgPerMin = (int)_playerStats[5];
            CSPerMin = (int)_playerStats[6];
            GoldPerMin = (int)_playerStats[7];
            return this;
        }
        
    }
}

排查建议

  • 枚举类型映射配置:MatchStatsLeague中的Role是枚举类型,EF Core 7需要明确其存储类型。在CDbContext中添加Fluent API配置:
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MatchStatsLeague>()
            .Property(m => m.Role)
            .HasConversion<int>(); // 或HasConversion<string>()根据需求选择
    }
    
  • 实体关联关系显式配置:部分导航属性使用default!初始化,EF Core可能无法自动识别关联。补充配置如:
    modelBuilder.Entity<Player>()
        .HasOne(p => p._team)
        .WithMany()
        .HasForeignKey(p => p.TeamId);
    
  • 值类型默认值修正:MatchStatsLeague中int属性设置为int.MinValue属于非典型默认值,建议改为0或允许为空:
    public int Kills { get; set; } = 0;
    // 或
    public int? Kills { get; set; }
    
  • DbContext注册校验:确保Program.cs中已正确注册DbContext并配置连接字符串:
    builder.Services.AddDbContext<CDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    

手动创建数据库与EF Core映射参考

  • 手动建库:通过SSMS或VS的SQL Server对象资源管理器直接创建数据库,定义表、主键、外键等结构。
  • 映射配置:使用数据注解(如[Key]、[ForeignKey]、[Table])或Fluent API完成实体与数据库表的映射。Fluent API适合复杂配置,比如多对多关系、索引、约束等。

内容的提问来源于stack exchange,提问作者Bearowl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 23:37:00