10.0: Adding Message Entity
We're going to build a messaging system. We'll start by adding a Message
entity that will act as a join entity similarly to our Follow
entity.
Add Message Entity
In your .Data/Entities
folder, add a new class called Message.cs
:
public class Message
{
public int Id { get; set; }
public int SenderId { get; set; }
public User Sender { get; set; }
public int RecipientId { get; set; }
public User Recipient { get; set; }
public string Content { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public DateTime DateSent { get; set; }
public bool SenderDeleted { get; set; }
public bool RecipientDeleted { get; set; }
}
We have the join properties - SenderId
/Sender
and RecipientId
/Recipient
. But, we're also collecting more information about the Message
than we did with the Follow
. Content
, IsRead
, DateRead
, and DateSent
are pretty self explanatory.
However, we have separate properties for SenderDeleted
and RecipientDeleted
. If one user deletes a message - we don't want to delete it for the other user as well. We'll only delete the message from the database if both users delete it.
Updating User Entity
We'll add two collection navigation properties on our User
entity: one for messages received and one for messages sent:
public ICollection<Message> MessagesSent { get; set; }
public ICollection<Message> MessagesReceived { get; set; }
Updating EFConnectContext
Next, we need to update our DbContext
. We'll start by adding a DbSet
property:
public DbSet<Message> Messages { get; set; }
Next, we'll configure it in the OnModelCreating()
method:
builder.Entity<Message>()
.HasOne(u => u.Sender)
.WithMany(u => u.MessagesSent)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<Message>()
.HasOne(u => u.Recipient)
.WithMany(u => u.MessagesReceived)
.OnDelete(DeleteBehavior.Restrict);
Run Migration and Update Database
In your terminal, navigate to the .Data
project and run the following command to add a new migration:
dotnet ef migrations add MessageEntity -s "../EFConnect.API/EFConnect.API.csproj"
Take a look at the migration and make sure it looks right, then run the following command to update the database:
dotnet ef database update -s "../EFConnect.API/EFConnect.API.csproj"
Here's an updated database diagram:

Last updated