There is one table (SqlCE) containing such columns.

[ID] ,[LastName] ,[FirstName] ,[Patronymic] ,[BirthDay] ,[DepartmentID] 

You need to add another column of type int (calculated), which will show the person's age for the current day, by calculating it from the [BirthDay] column. How can I do that ? Interested in two approaches

  1. Make it through Sql query to this table (if it is possible)
  2. Through Entity Model Constructor.
  3. Get the number of years with a simple Sql query that somehow converts the date of birth into the number of years

Thanks to all

  • What kind of DBMS do you use ? MaxU
  • @MaxU Sql CE 4.0, through the standard VS 2015 tool (SQL Server Compact / SQLite Toolbox) - Polyakov Sergey

2 answers 2

Request to the database:

 SELECT [ID] ,[LastName] ,[FirstName] ,[Patronymic] ,[BirthDay] ,[DepartmentID] ,DATEDIFF(YEAR, [BirthDay], GETDATE()) AS Age FROM SqlCE; 

This is if you want to get data, for example, using SqlCommand

In the Entity Framework, you can add a calculated field with the NotMapped attribute, it is natural to add it to the non-generated part of the entity (if you are using DB First)

 partial class SqlCE { [NotMapped] public int Age { get { return (DateTime.Now - Birthday).Days / 365; } private set {} } } 
  • Thanks for the answer, please tell me, but where do I need to add this class, which is with the framework? - Polyakov Sergey
  • 2
    @PolyakovSergey Well, if you have a Code First approach, then right into the entity class, marking NotMapped . If the DB First approach, then with each generation of classes from db, the source code will be rewritten, scoring all your code. But since Entity - partial class , you get a separate source code in the same namespace, write partial class [Ваше имя сущности] {} and add your computable fields, functions, etc. there. - Mirdin

Try adding Computed Column :

 ALTER TABLE TableName ADD Age AS datediff(year, BirthDay ,getdate()); 

PS I can not test (not on anything), so do not judge if something is wrong ...