I am currently trying to add an message column to my table which is modelled to look like this
public class Notification
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
public string ActionType { get; set; } = string.Empty;
public string ActionElement { get; set; } = string.Empty;
public string ActionElementType { get; set; } = string.Empty;
public User ForUser { get; set; } = new User();
public User ByUser { get; set; } = new User();
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool Seen { get; set; } = false;
public bool Clicked { get; set; } = false;
public Dictionary<string, string>? MessageProperties { get; set; }
public string Message { get; set; }
}
I want it to look like this
public class Notification
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
public string ActionType { get; set; } = string.Empty;
public string ActionElement { get; set; } = string.Empty;
public string ActionElementType { get; set; } = string.Empty;
public User ForUser { get; set; } = new User();
public User ByUser { get; set; } = new User();
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool Seen { get; set; } = false;
public bool Clicked { get; set; } = false;
public Dictionary<string, string>? MessageProperties { get; set; }
public Message MessageContent { get; set; }
}
public record Message
{
[Key]
public Guid MessageId { get; set; } = Guid.NewGuid();
public string? MessageContent { get; init; }
public Dictionary<string, string>? MessageContentProperties { get; init; }
}
I have via EF managed to make a migrations, but have some issues applying it.
The error message i get when I apply it is
ERROR: insert or update on table "Notifications" violates foreign key constraint "FK_Notifications_Message_MessageContentMessageId"
DETAIL: Key (MessageContentMessageId)=(00000000-0000-0000-0000-000000000000) is not present in table "Message".
which I am not sure I understand why and how i should fix.
It fails when it tries to do this
ALTER TABLE "Notifications"
ADD COLUMN "MessageContentMessageId" uuid DEFAULT uuid_nil() NOT NULL
2
Answers
Try making the relationship nullable:
It seems that you have nullable reference types enabled so EF Core will consider the relationship required and will try to insert the default
Guid
value.Read more:
first of all remove default value of
MessageId
and make theMessageId
property nullable, then change theNotification
class to use theMessageId
property from theMessage
classnow generate a new migration and then apply the migration to update the database like below