kakon
kakon

Reputation: 721

How to Save string property with foreign key reference in database

I am working on an asp.net mvc project using entity framework and sql database. On some action i want to save a notification message which contains reference of another model User

the two models are as follows

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 add a new notificationmessage to my database table and the message property is like

"new notification from user"+FromUser.Name

Now if i change User's Name this message does not change as it is saved as static message in database. what i want is that this message will be saved in database in a way that if i change user's Name property this message will show the updated Name of User

Upvotes: 3

Views: 356

Answers (1)

haim770
haim770

Reputation: 49105

If you're persisting a bare string into the database, it will remain a string even if it's constructed using some data from related entity. The expression used to construct that string would not be re-evaluated each time you're accessing it (regardless of EF, that's natural string behavior).

You better change your Message to a computed property:

public string Message
{
    get { return "new notification from user" + FromUser.Name; }
}

Upvotes: 1

Related Questions