Ошибка миграции EF Core 7: ссылка на объект не установлена ​​на экземпляр объектаC#

Место общения программистов C#
Anonymous
Ошибка миграции EF Core 7: ссылка на объект не установлена ​​на экземпляр объекта

Сообщение Anonymous »

Использование VS22 в качестве IDE, EF Core (версия 7.0.5) в качестве ORM и LocalDB с подходом «сначала код» при попытке создать миграцию через:

Код: Выделить всё

dotnet ef migrations add Test
Я получаю следующий результат:

Код: Выделить всё

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.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.
Общая концепция проекта заключается в создании приложения для облегчения хобби-лиг по видеоиграм. Может быть, кто-нибудь сможет мне помочь, потому что я не могу понять, почему возникает эта проблема. Я знаю, что существует ссылка на объект, не установленная для объекта, но я не могу найти ее, хоть убей.
Я впервые действительно работаю с EF Core, и на данный момент я был бы в порядке, создав это. Сопоставление БД и EF Core вручную, поэтому, если есть хорошая документация или руководство, я был бы благодарен за ссылку или что-то в этом роде.
Это мой DBContext

Код: Выделить всё

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
 players => Set();
public DbSet teams => Set();
public DbSet leagues => Set();
public DbSet matches => Set();
public DbSet matchstatsleague => Set();
#endregion

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

#region methods
public bool SaveAllChanges()
{
var records = SaveChanges();
return records > 0;
}
#endregion
}
}
И вот классы, которые я пытаюсь внести в базу данных:
Игроки, входящие в Лигу

Код: Выделить всё

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
}
}
Участвующие команды

Код: Выделить всё

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 _player { get; set; } = default!;
//public League _league { get; set; }
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
}
}
Лиги, в которые входят команды

Код: Выделить всё

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 _teams { get; set; } = default!;
[NotMapped] public Dictionary _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
}
}
Матчи между разными командами

Код: Выделить всё

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 TeamBlueStats { get; set; } = default!;
[NotMapped] public Dictionary 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
}
}
И MatchStats — это статистика, которую каждый из игроков накапливает в матче, со ссылкой на лигу, матч и игрока.

Код: Выделить всё

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;
}

}
}
Буду благодарен за любые советы и подсказки, а также за то, что нашли время прочитать все это

Подробнее здесь: https://stackoverflow.com/questions/764 ... -an-object

Вернуться в «C#»