Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Entity Framework Core updates time Mappin

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces Entity Framework Core how to update the time mapping, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Time field

In real development, in order to track changes in data, there are usually two columns CreatedTime and UpdatedTime in the data table. CreatedTime indicates the creation time, and the value of the CreatedTime column is updated when a new piece of data is added. UpdatedTime indicates the update time, and the value of the UpdatedTime column will also be updated when the data is updated, so the corresponding mapping is needed to configure it. We modify the Blog class to add these two time fields:

Using System;namespace EFCore.Model {public class Blog {public int Id {get; set;} public string Name {get; set;} / public DateTime CreatedTime {get; set;} / add time / public DateTime UpdatedTime {get; set;}

Do not make any configuration at this time, use migration to generate the database, and view the database table structure:

You can see that what is generated in the database is of datetime2 type, and the precision of datetime2 is very high. But in general, do not use datetime2 high-precision, use datetime on it, then we need to do our own mapping to configure and generate datetime types.

Modify the data context class and add the mapping configuration of the time field, as follows:

Using EFCore.Model;using Microsoft.EntityFrameworkCore;namespace EFCore.Data {/ data context / public class EFDbContext: DbContext {protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ("Data Source=.;Initial Catalog=EFTest;User ID=sa;Password=123456;");} public DbSet Blogs {get; set } / override the OnModelCreating method to configure the mapping / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / configuration table name mapping modelBuilder.Entity () .ToTable ("Blog") / / an error will be reported if the length of the table name is set to 250. the maximum length of the table name is limited to var tableName = string.Join (",", Enumerable.Repeat ("t", 250). ToArray ()); / / modelBuilder.Entity () .ToTable (tableName) ModelBuilder.Entity (p = > {/ / configure CreatedTime field p.Property (t = > t.CreatedTime) / / sets the type of the column to be DATETIME .HasColumnType ("DATETIME") / / sets the default value of the column .HasDefaultValueSql ("GETDATE ()") / / configure the UpdatedTime field p.Property (t = > t.UpdatedTime) / / set the type of the column to DATETIME .HasColumnType ("DATETIME") / / set the default value of the column. HasDefaultValueSql ("GETDATE ()");}); base.OnModelCreating (modelBuilder) }}}

Generate the database table using data migration, and then view the data type of the column:

At this point, the data type of the time column is datetime. Set the default value for the time field in the code, add a piece of seed data, and then add it to the database to see if the default value will be automatically generated:

You can see from the screenshot that when adding data, CreatedTime and UpdatedTime will automatically assign the value of the current time. Before modifying the seed data you just added, see if the value of the UdpatedTime column will be updated:

You can see that the value of the Name column has been changed, but the value of the UpdatedTime column has not been updated. But what we want is that when the data is updated, the value of the UpdatedTime column is also updated. What should we do? There are two ways to solve this problem.

1. Use computed columns

The way to do this is to set the computed column for the UpdatedTime field as follows:

Using EFCore.Model;using Microsoft.EntityFrameworkCore;namespace EFCore.Data {/ data context / public class EFDbContext: DbContext {protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ("Data Source=.;Initial Catalog=EFTest;User ID=sa;Password=123456;");} public DbSet Blogs {get; set } / override the OnModelCreating method to configure the mapping / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / configuration table name mapping modelBuilder.Entity () .ToTable ("Blog") / / an error will be reported if the length of the table name is set to 250. the maximum length of the table name is limited to var tableName = string.Join (",", Enumerable.Repeat ("t", 250). ToArray ()); / / modelBuilder.Entity () .ToTable (tableName) ModelBuilder.Entity (p = > {/ / configure CreatedTime field p.Property (t = > t.CreatedTime) / / sets the type of the column to be DATETIME .HasColumnType ("DATETIME") / / sets the default value of the column .HasDefaultValueSql ("GETDATE ()") / configure the UpdatedTime field / / p.Property (t = > t.UpdatedTime) / set the type of the column to DATETIME / / .HasColumnType ("DATETIME") / set the default value of the column / / .HasDefaultValueSql ("GETDATE ()") / / configure the UpdatedTime field p.Property (t = > t.UpdatedTime) / / set the column type to DATETIME .HasColumnType ("DATETIME") / / set the UpdatedTime field to use the calculated column .HasComputedColumnSql ("GETDATE ()");}) / / add a seed data modelBuilder.Entity () .HasData (new Blog () {Id=1, Name= "ef core 3.1.2"}); base.OnModelCreating (modelBuilder);}

Then delete the database, generate the database from scratch, add new data, and modify the data. Let's take a look at the results of the new data:

As you can see, CreatedTime and UpdatedTime will have errors at this time, but the errors are acceptable within seconds. We are looking at the revised results:

At this point, you will find that the value of the UpdatedTime column will change. You will also find that the data type of the UpdatedTime column is calculated:

2. Override the SaveChanges method

Another way is to override the SaveChanges () method.

Let's first define an IUpdatedable interface in the entity class library:

Using System;namespace EFCore.Model {public interface IUpdatedable {DateTime UpdatedTime {get; set;}

The Blog class then inherits from this interface:

Using System;namespace EFCore.Model {public class Blog:IUpdatedable {public int Id {get; set;} public string Name {get; set;} / public DateTime CreatedTime {get; set;} / add time / public DateTime UpdatedTime {get; set;}

Then override the SaveChanges method in the data context class:

Public override int SaveChanges () {var entries = ChangeTracker.Entries (). ToList (); var updateEntries = entries.Where (e = > (e.Entity is IUpdatedable) & & e.State = = EntityState.Modified). ToList (); updateEntries.ForEach (e = > {((IUpdatedable) e.Entity). UpdatedTime = DateTime.Now;}); return base.SaveChanges ();}

At the same time, the UpdatedTime field is not a calculated column, and the default value is assigned:

/ / configure the UpdatedTime field p.Property (t = > t.UpdatedTime) / / set the type of column to DATETIME.HasColumnType ("DATETIME") / / set the default value of the column. HasDefaultValueSql ("GETDATE ()")

Data migration cannot be used in this way, but can only be achieved by calling the SaveChanges method in the code:

Using EFCore.Data;using EFCore.Model;using System;namespace EFCore.Con {class Program {static void Main (string [] args) {Console.WriteLine ("Hello World!"); / / instantiate the data context object EFDbContext dbContext = new EFDbContext (); / / generate database bool tfTrue = dbContext.Database.EnsureCreated () If (tfTrue) {Console.WriteLine ("database created successfully!");} else {Console.WriteLine ("database creation failed!");} / / query data with Id 1 var blog = dbContext.Blogs.Find (1) / / change the table name blog.Name = "entity framework core 3.1.21212"; dbContext.SaveChanges (); Console.ReadKey ();}

Database effect:

This also completes the update.

Thank you for reading this article carefully. I hope the article "how to update the time map of Entity Framework Core" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report