JustLearning
JustLearning

Reputation: 3332

ASP MVC code first create computed primary key

I am using code first in asp mvc and i came across a situation where i need to have a model/table with a computed primary key for example:

 public class Student
{
    [Key]
    public string StudentNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime RegistrationDate { get; set; }

}

So is there a way to make the StudentNumber to be computed by for example taking 1st letter of the LastName, the year of registration and an autoincrement number?

Upvotes: 1

Views: 82

Answers (1)

ediblecode
ediblecode

Reputation: 11971

For performance reasons, you really don't want to have your primary key as a string, so question where this requirement is coming from. However:

[Key]
public int Id { get; set; }

[NotMapped]
public string StudentId 
{ 
    get 
    { 
        return string.Format("{0}{1}{2}", 
            this.LastName.Substring(0, 1), 
            this.RegistrationDate.Year,
            this.Id);
    }
}

Upvotes: 2

Related Questions