I have these relevant tables in an MVC website:
Server
ServerPlayer
ServerPlayerChat
Servers have serverPlayers
and ServerPlayers
have ServerPlayerChats
. Simple enough and expectable.
I have a feeling my code could be drastically condensed (particularly the GetServerPlayer
method) and that the GetServerPlayer
method is named wrong, although I couldn't think of a better name other than GetOrCreateServerPlayer
, which is really long-winded. Also, this is in the Server model. I think I could move the add chat to the server player model, but my concern is that this might be more appropriate in a controller.
Is it good practice to do what I'm doing where I'm not only adding the new chat to the ServerUserChats
collection, but also setting ServerPlayer = player
inside the new chat? I'm aware that LINQ/EF/... is capable of figuring out relations like this from just one variable but it felt right to do this, so feedback on that is accepted too.
public void AddChat(string playername, string chat, int time)
{
LastChat = time;
ServerPlayer player = GetServerPlayer(playername);
player.ServerUserChats.Add(new ServerPlayerChat() {
Content = chat,
Time = time,
ServerPlayer = player
});
}
public ServerPlayer GetServerPlayer(string playername)
{
ServerPlayer player = GetPlayer(playername);
if (player == null)
{
player = new ServerPlayer() {
Server = this,
UserName = playername,
};
Players.Add(player);
}
return player;
}
public ServerPlayer GetPlayer(string playername)
{
return Players.Where(x => x.UserName == playername).FirstOrDefault();
}