1

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?

4

1 回答 1

2

出于性能原因,您确实不希望将主键作为字符串,因此请质疑此要求的来源。然而:

[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);
    }
}
于 2016-02-29T09:40:23.583 回答