How to store a string property with a foreign key reference in a database
I am working on an asp.net mvc project using entity framework and sql database. On any action, I want to keep a notification containing a link to another User model
the two models are:
public class NotificationMessage
{
[Key]
public int Id { get; set; }
public int? FromUserId { get; set; }
[ForeignKey("FromUserId")]
public virtual User FromUser { get; set; }
public string Message { get; set; }
}
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string Name{ get; set; }
}
Now on some action I am adding a new notification message to my database table and the message property is like
"new notification from user" + FromUser.Name
Now, if I change the username, this message does not change as it is stored as a static message in the database. what I want is that this message will be saved in the database in such a way that if I change the username property this message will show the updated username
source to share
If you store naked string
in the database, it will remain string
even if created using some data from the associated object. The expression used to construct this string will not be re-read every time you access it (regardless of EF, this natural behavior string
).
Better to change yours Message
to a computed property:
public string Message
{
get { return "new notification from user" + FromUser.Name; }
}
source to share