为什么我在这个上遇到错误?我想要类型的ID ...在数据库中,游戏表在类型表中有genre_id的外键。
public List<Game> GetGames()
{
List<Game> games = new List<Game>();
try
{
conn.Open();
string selectQuery = "select * from game";
MySqlCommand cmd = new MySqlCommand(selectQuery, conn);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
string gameNaam = dataReader.GetString("gamenaam");
int gameId = dataReader.GetInt32("game_id");
int genreId = dataReader.GetInt32("genre_id");
Game game = new Game { ID = genreId, game.Genre.ID = genreId, Naam = gameNaam};
games.Add(game);
}
}
catch (Exception e)
{
Console.Write("Ophalen van genres mislukt " + e);
}
finally
{
conn.Close();
}
return games;
}
}
我在这个上面收到错误-----&gt; game.Genre.ID = genreId
代码类型和游戏:
public class Game
{
public String Naam { get; set; }
public Genre Genre { get; set; }
public int ID { get; set; }
public override string ToString()
{
return String.Format("{0} (id = {1})", Naam, ID);
}
}
public class Genre
{
public string Naam { get; set; }
public bool Verslavend { get; set; }
public int ID { get; set; }
public override String ToString()
{
return String.Format("{0} ({1})", Naam,
Verslavend ? "Verslavend" : "Niet verslavend");
}
}
答案 0 :(得分:1)
这是无效的语法:
new Game { ID = genreId, game.Genre.ID = genreId, Naam = gameNaam};
^--- here
game
在该上下文中不存在。你也不能在这样的属性初始化器中设置子属性。
如果要设置Genre
属性,则必须自行设置。像这样:
new Game {
ID = genreId,
Genre = new Genre {
ID = genreId
},
Naam = gameNaam
};