2

I have a database where I'm trying to add messages and I use channelID for LiteDB id. I want to post more than 1 message in the same channel somehow but for that I would have to use the same ID somehow.

   private LiteDatabase Database { get; } = new LiteDatabase(@"data/msg.db");

    public ILiteCollection<Message> Messages { get { return Database.GetCollection<Message>("Messages"); } }

    public void Add(int channelid, Message message)
    {
        message.ChannelID = channelid;
        Messages.Insert(message);

        //Books.Add(book.Id,book);
    }

Message class

public class Message
{
    [LiteDB.BsonId]
    public int ChannelID { get; set; }

    public int User { get; set; }

    public DateTime Date { get; set; }

    public string Text { get; set; }
}

This is the API I want to replicate: http://www.webservies.be/chat/swagger/index.html In this it's possible to use the same channelID when I want to POST a message.

amur567
  • 67
  • 6
  • I think you might've overlooked something in the design. You expect `ChannelId` to be an `BsonId` (unique), but want to use the same Id. Imagine trying to get a specific message by ChannelId if they weren't unique - which one would you expect to get back? You need another entity (like `Channel`) which Message has a many-to-one relationship with. The API you posted above has this relationship. – Ben Sampica May 31 '20 at 16:27
  • Hmm thanks. I'm a beginner at coding so I don't really know much about many-to-one relationships or about how should I add that other entity. I will try to figure something out tho. – amur567 May 31 '20 at 18:03
  • Let me add something for you. – Ben Sampica May 31 '20 at 18:04

1 Answers1

2

If you want your class to match the API you posted, you'll need an additional Channel class with a one-to-many relationship with Message. One chat channel can have many messages, right?

Something like

public class Channel
{
    [BsonId]
    public int ChannelId { get; set; }
    public string Name { get; set; }

    [BsonRef]
    public List<Message> Messages { get; set; }
}

public class Message
{
    [BsonId]
    public int MessageId { get; set; }
    public int ChannelId { get; set; }
    public int UserId { get; set; }
    public DateTime Date { get; set; }
    public string Text { get; set; }
}

Inserting a new message would be very similar to what you've already done.

public void Add(int channelId, string text, int userId)
{
   var message = new Message {
       ChannelId = channelId,
       Text = text,
       UserId = userId,
       Date = DateTime.Now
   };

   Messages.Insert(message);
}
Ben Sampica
  • 2,912
  • 1
  • 20
  • 25