dotnet ef migrations add Test
< /code>
Я получаю следующий вывод: < /p>
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.
< /code>
Общая концепция проекта заключается в создании приложения для облегчения хобби для видеоигры. Может быть, кто -то может мне помочь, потому что я не могу найти, почему возникает эта проблема. Я знаю, что есть объект, не установленная на объект, но я не могу в течение жизни, где я найду, где.
Это мой первый раз, когда я действительно работаю с EF Core, и на данный момент я был бы в порядке, создавая этот DB и ядро EF вручную, поэтому, если есть хорошая документация или учебник для этого, я буду благодарен о ссылке или что -то в руках.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
}
}
< /code>
И это те классы, которые я пытаюсь работать в базе данных:
игроки, которые являются частью лиги < /p>
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
}
}
< /code>
Участвующие команды < /p>
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
}
}
< /code>
Лиги, содержащие команды < /p>
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
}
}
< /code>
совпадает между разными командами < /p>
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
}
}
< /code>
и Matchstats Это статистика, которые каждый из игроков накапливает в матче со ссылками на лигу, матч и игрока < /p>
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;
}
}
}
Я был бы благодарен за любые советы и указатели и спасибо, что нашли время, чтобы прочитать все это
Использование VS22 в качестве IDE, EF Core (версия 7.0.5) в качестве ORM и LocalDB с кодом первого подхода, при попытке создать миграцию через: < /p> [code]dotnet ef migrations add Test < /code> Я получаю следующий вывод: < /p> 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. < /code> Общая концепция проекта заключается в создании приложения для облегчения хобби для видеоигры. Может быть, кто -то может мне помочь, потому что я не могу найти, почему возникает эта проблема. Я знаю, что есть объект, не установленная на объект, но я не могу в течение жизни, где я найду, где. Это мой первый раз, когда я действительно работаю с EF Core, и на данный момент я был бы в порядке, создавая этот DB и ядро EF вручную, поэтому, если есть хорошая документация или учебник для этого, я буду благодарен о ссылке или что -то в руках.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 } } < /code> И это те классы, которые я пытаюсь работать в базе данных: игроки, которые являются частью лиги < /p> 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 } } < /code> Участвующие команды < /p> 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 } } < /code> Лиги, содержащие команды < /p> 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 } } < /code> совпадает между разными командами < /p> 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 } } < /code> и Matchstats Это статистика, которые каждый из игроков накапливает в матче со ссылками на лигу, матч и игрока < /p> 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
Использование VS22 в качестве IDE, EF Core (версия 7.0.5) в качестве ORM и LocalDB с подходом «сначала код» при попытке создать миграцию через:
dotnet ef migrations add Test
Я получаю следующий результат:
Build started...
Build succeeded....
Мы создали приложение для настольного компьютера .NET с использованием LattePanda для чтения данных датчика с печатной платы с использованием протокола связи RS485. Код C# использует библиотеку EasyModbus для чтения данных. Приложение работает в...
Я понятия не имею, почему это происходит или где. Ошибка не предоставляет номера строки. Это ошибка во всей его полноте:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
at...
Итак, я сделал DLL для генерации токена аутентификации в C# (.NET Framework v4.8) с тестовым пользовательским интерфейсом, чтобы проверить, что он работает, что делает. Появляется экран входа в систему, я могу войти в систему и генерировать токен...
Итак, я сделал DLL для генерации токена аутентификации в C# (.NET Framework v4.8) с тестовым пользовательским интерфейсом, чтобы проверить, что он работает, что делает. Появляется экран входа в систему, я могу войти в систему и генерировать токен...