我從另一臺服務器獲取 JSON 檔案,對其進行反序列化并嘗試添加我的 C# 物件,然后將其保存在我的資料庫中。問題是我無法保存這些資料。我沒有收到任何錯誤,我不確定我做錯了什么。這是我的代碼:
public class GameRepository : IGameRepository
{
private readonly GameDbContext _context;
//private readonly IMapper<Game, GameModel> _gameMapper;
public GameRepository(GameDbContext context)
{
_context = context;
}
}
string catJson;
string gameJson;
using (WebClient _web = new WebClient())
{
catJson = _web.DownloadString(_catUri);
}
var gamecatss = JsonConvert.DeserializeObject<List<Category>>(catJson);
using (WebClient _web = new WebClient())
{
gameJson = _web.DownloadString(_uri);
}
var games = JsonConvert.DeserializeObject<List<Games>>(gameJson);
List<Games> gameModels = new List<Games>();
gameModels.AddRange(games);
List<Category> categoryModels = new List<Category>();
categoryModels.AddRange(gamecatss);
_context.SaveChanges();
return JsonConvert.SerializeObject(games);`
這是我的 DbContext:
public partial class GameDbContext : DbContext
{
public GameDbContext()
{
}
public GameDbContext(DbContextOptions<GameDbContext> options) :
base(options)
{
}
public virtual DbSet<Category> Category { get; set; }
public virtual DbSet<Games> Games { get; set; }`
這是我的存盤庫:
public class GameRepository : IGameRepository
{
private readonly GameDbContext _context;
//private readonly IMapper<Game, GameModel> _gameMapper;
public GameRepository(GameDbContext context) { _context = context; }
}
public partial class Games
{
public int Id { get; set; }
public string System { get; set; }
public string SubSystem { get; set; }
public string PageCode { get; set; }
public string LowRtpUrl { get; set; }
public string LowRtpMobileUrl { get; set; }
public string LowRtpUrlExternal { get; set; }
public string LowRtpMobileUrlExternal { get; set; }
public string MobilePageCode { get; set; }
public string MobileAndroidPageCode { get; set; }
public string MobileWindowsPageCode { get; set; }
public string CustomSortType { get; set; }
public string ImageUrl { get; set; }
}
id在這里是PK。類別類看起來相似。PS回傳作業正常,它也正確顯示資料。
一看它應該可以作業,我的游戲類和類別類都很好。我敢肯定,我給他們搭建了腳手架,有什么想法我做錯了嗎?
uj5u.com熱心網友回復:
你需要這樣的東西
var games = JsonConvert.DeserializeObject<List<Games>>(gameJson);
var gamecatss = JsonConvert.DeserializeObject<List<Category>>(catJson);
// remove Ids
games.ForEach(x => x.Id = 0);
gamecatss.ForEach(x => x.Id = 0);
_context.Games.AddRange(games);
_context.Category.AddRange(gamecatss);
_context.SaveChanges();
uj5u.com熱心網友回復:
所以最后我發現我做錯了什么
var games = JsonConvert.DeserializeObject<List<Games>>(gameJson);
var gamecatss = JsonConvert.DeserializeObject<List<Category>>(catJson);
List<GamesDTO> gameModels = new List<GamesDTO>()
List<CategoryDTO> categoryModels = new List<CategoryDTO>();
_context.Games.AddRange(games);
_context.Category.AddRange(gamecatss);
_context.SaveChanges();
我在 forech 回圈中進行了映射以從 DTO 映射到游戲模型,然后保存并且效果很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/521075.html
上一篇:帶有連接節點的鏈接的聚集氣泡
