Есть модели
public class Server
{
public string Endpoint { get; set; }
public Info Info { get; set; }
[JsonIgnore]
public int Id { get; set; }
}
public class Info
{
public Info()
{
InfoGameMods = new List<InfoGameMode>();
}
public string Name { get; set; }
[JsonIgnore]
public List<InfoGameMode> InfoGameMods { get; set; }
[NotMapped]
public string[] GameMods
{
get
{
string[] gm = new string[InfoGameMods.Count];
for (int i = 0; i < gm.Length; i++)
gm[i] = InfoGameMods[i].GameMode.Name;
return gm;
}
set
{
ServerContext context = new ServerContext();
foreach (var gm in value)
{
GameMode gameMode = context.GameMods.Where(_gm => _gm.Name == gm).FirstOrDefault();
if (gameMode == null)
{
gameMode = new GameMode { Name = gm };
context.GameMods.Add(gameMode);
InfoGameMode igm = new InfoGameMode
{
GameMode = gameMode,
Info = this
};
InfoGameMods.Add(igm);
}
}
}
}
[JsonIgnore]
public int Id { get; set; }
}
public class InfoGameMode
{
public int InfoId { get; set; }
public Info Info { get; set; }
public int GameModeId { get; set; }
public GameMode GameMode { get; set; }
}
public class GameMode
{
public GameMode()
{
InfoGameMods = new List<InfoGameMode>();
}
public string Name { get; set; }
[JsonIgnore]
public int Id { get; set; }
[JsonIgnore]
public List<InfoGameMode> InfoGameMods { get; set; }
}
public class ServerContext : DbContext
{
public DbSet<Info> Info { get; set; }
public DbSet<Server> Servers { get; set; }
public DbSet<GameMode> GameMods { get; set; }
public DbSet<InfoGameMode> InfoGameMods { get; set; }
public ServerContext()
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<InfoGameMode>()
.HasKey(t => new { t.InfoId, t.GameModeId });
modelBuilder.Entity<InfoGameMode>()
.HasOne(igm => igm.Info)
.WithMany(gm => gm.InfoGameMods)
.HasForeignKey(igm => igm.InfoId);
modelBuilder.Entity<InfoGameMode>()
.HasOne(igm => igm.GameMode)
.WithMany(info => info.InfoGameMods)
.HasForeignKey(igm => igm.GameModeId);
}
}
Пытаюсь сделать это
public void Info([FromBody]Server server)
{
db.Servers.Add(server);
db.SaveChanges();
}
но при запуске этого метода - SqlException: "Cannot inserte explicit value for identity column un table "GameMods" when IDENTITY_INSERT is set to OFF".
Как я понимаю, ошибка значит, что я пытаюсь явно присвоить индекс, в то время как "insert_identity off")
И, скорее всего дело в блоке set свойства GameMods модели Info(не уверен что его правильно написал).
А зачем там такой set? Надо сериализовать данный объект в json, а поле "GameMods" должно быть строкой, но при этом надо хранить сами "gamemods". Получается я get-ом возвращаю массив строк. А вот set-ом надо как-то занести массив строк в бд, притом используется связь "многие к многим"(несколько gamemode на несколько info) с помощью введения доп модели InfoGameMode(EF Core). Как-то так)