public class Message { [Key, Column(Order = 1)] public int UserId {get;set;} [Key, Column(Order = 2)] public int MessageId {get;set;} public string Body {get;set;} } 

There is an essence Message. Is it possible to somehow automatically generate a MessageId when added within a single UserId?

And if not, is this option acceptable?

 int userId = 1; var message = new Message(); int lastMessageId = db.Messages.Where(m=>m.UserId==userId).OrderByDescending(m=>m.MessageId).First().MessageId; message.MessageId = lastMessageId + 1; db.Messages.Add(message); 
  • In the proposed version, it is far more effective not to select all the id to sort and take them first, but simply to find the maximum. - teran
  • in particular, the proposed option will cause an exception in the case where the user does not have associated messages. - teran
  • as an alternative to filling the field, you can suggest using a trigger to insert data into the table. Although the meaning of storing message numbers for each user as a whole is not very clear, for sure there will also be some sort of time stamp. - teran

0