There is a ready base in which nothing can be added. I made edmx out of it in the project. Now I need to add a calculated field that calculates age. I add the Age property to the essence, but the crash crashes.

Entity code:

public partial class Employee { public System.Guid ID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string Patronymic { get; set; } public Nullable<System.DateTime> BirthDay { get; set; } public Nullable<System.Guid> DepartmentID { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int Age { get { if (BirthDay != null) return (DateTime.Now - BirthDay.Value).Days / 365; return 0; } set { } } } 

Self Exception

The LINK to Entities is a specified type of member. Only initializers, entity members, and entity navigation properties are supported.

How can I add a calculated field in my case?

    1 answer 1

    Depends on how to use this property when calling.

    This is how you get an error:

     using (var context = new MyContext()) { /* FirstOrDefault() применяется к типу IQueryable<Employee> В этом случае на стороне БД выполнится примерно такой запрос: SELECT * FROM [dbo].[Employee] WHERE Age = 27 Но т.к. в таблице нет поля Age то выходит ошибка */ var myEmployee = context.Employee.FirstOrDefault(x => x.Age == 27); } 

    But there will be no error:

     using (var context = new MyContext()) { /* FirstOrDefault() применяется к типу IEnumerable<Employee> В этом случае сначала сервер БД отдаст все элементы из таблицы Employee и только потом клиент (приложение) в памяти посчитает Age. */ var myEmployee = context.Employee.AsEnumerable().FirstOrDefault(x => x.Age == 27); }