Business-logic type methods in Entity Framework Code First approach classes

Of course it is, with the caveat that the value of StudentNamePlusALetter() won't be stored in your database (since only properties get serialized down there).


I usually do this by have 2 "partial" classes. One for the straight-up mapped database properties. One for the extra stuff.

In a file called Employee.cs

public partial class Employee
{
    public Employee()
    {

    }

    public System.Guid EmployeeUUID { get; set; }

    public string SSN { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public System.DateTime ? CreateDate { get; set; }
    public System.DateTime HireDate { get; set; }

}

Then in a file called EmployeeExtended.cs

public partial class Employee
{
    public string EmployeeFullName
    {
        get
        {
            return string.Format("{0}, {1} ('{2}')", this.LastName, this.FirstName, this.SSN);
        }
    }


}

Note in the above, I have a readonly ("get") property ("EmployeeFullName") that will work fine with EF, no changes required.

I can also do this:

public partial class Employee
{
    public string EmployeeFullName
    {
        get
        {
            return string.Format("{0}, {1} ('{2}')", this.LastName, this.FirstName, this.SSN);
        }
    }

    public string SomeNonTrackedDatabaseProperty { get; set; }

}

But then I have to add an ".Ignore" in the Mapping for "SomeNonTrackedDatabaseProperty", since it is not a column in the database..

 public class EmployeeMap : EntityTypeConfiguration<Employee>
    {
        public EmployeeMap()
        {
            // Primary Key
            this.HasKey(t => t.EmployeeUUID);


            this.Property(t => t.SSN)
                .IsRequired()
                .HasMaxLength(11);

            this.Property(t => t.LastName)
                .IsRequired()
                .HasMaxLength(64);

            this.Property(t => t.FirstName)
                .IsRequired()
                .HasMaxLength(64);

            // Table & Column Mappings
            this.ToTable("Employee");
            this.Property(t => t.EmployeeUUID).HasColumnName("EmployeeUUID");

            this.Property(t => t.SSN).HasColumnName("SSN");
            this.Property(t => t.LastName).HasColumnName("LastName");
            this.Property(t => t.FirstName).HasColumnName("FirstName");
            this.Property(t => t.CreateDate).HasColumnName("CreateDate");
            this.Property(t => t.HireDate).HasColumnName("HireDate");



            this.Ignore(t => t.SomeNonTrackedDatabaseProperty);


        }
    }
}