static void Main(string[] args) { var context = new ChatDbContext(); var channels = context.Channels .Include(x => x.ChannelMessages) .Include("ChannelMessages.User") .Select(x => new { x.Name, ChannelMessages = x.ChannelMessages.Select(c => new { c.Content, c.DateTime, c.User.Username }) }); foreach (var channel in channels) { Console.WriteLine(channel.Name); Console.WriteLine("-- Messages: --"); foreach (var channelMessage in channel.ChannelMessages) { Console.WriteLine("Content: {0}, DateTime: {1}, User: {2}", channelMessage.Content, channelMessage.DateTime, channelMessage.Username); } Console.WriteLine(); } }
private static void ImportMessageToDatabase(MessageDto message) { if (string.IsNullOrWhiteSpace(message.Content)) { throw new ArgumentException("Content is required"); } if (string.IsNullOrWhiteSpace(message.Recipient)) { throw new ArgumentException("Recipient is required"); } if (string.IsNullOrWhiteSpace(message.Sender)) { throw new ArgumentException("Sender is required"); } var context = new ChatDbContext(); var recipientId = context.Users .Where(x => x.Username == message.Recipient) .Select(x => x.Id) .FirstOrDefault(); var senderId = context.Users .Where(x => x.Username == message.Sender) .Select(x => x.Id) .FirstOrDefault(); var newMessage = new UserMessage { Content = message.Content, DateTime = message.DateTime, RecipientId = recipientId, SenderId = senderId }; context.UserMessages.Add(newMessage); context.SaveChanges(); }