In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "how Entity Framework Core generates columns and tracks column records". The content is detailed, the steps are clear, and the details are handled properly. I hope this "Entity Framework Core how to generate columns and track column records" article can help you solve your doubts.
Note: I am using Entity Framework Core 2.0 (2.0.0-preview2-final). There may be changes in functionality when the official version is released.
When you design a database, you sometimes need to add columns to keep track of when and who made the changes. For example, you add the following:
CreatedAt
CreatedBy
LastUpdatedAt
LastUpdatedBy
You can easily use default values and triggers to process CreatedAt and LastUpdatedAt columns. To be honest, creating triggers is boring, and you don't want to do it yourself. In addition, it is difficult to set the user name because it is application information; in fact, in the context of the Web program, they are just a user connected to the database, so you cannot use the CURRENT_USER function in the database to set the value of the trace column.
Of course, you don't want to access this property. Instead, you want Entity Framework to execute automatically for you, so the solution is to automatically set the values of these properties before calling the SaveChanges or SaveChangesAsync methods. There are several ways to deal with these attributes in the model: you can add read-write (R _ Shadow W) attributes to the model; you can also use read-only (R _ hand O) attributes; and in another scenario, you can use the shadow (shadow) attribute. In the last scenario, columns are not mapped to attributes in the model, which are known only to Entity Framework. Yes, EF Core is very flexible:)
We use Entity Framework to achieve these three schemes!
Read-write attribute
In this case, the entity will have read / write attributes. This means that you can change the value of the property in the code.
Public interface ITrackable {DateTime CreatedAt {get; set;} string CreatedBy {get; set;} DateTime LastUpdatedAt {get; set;} string LastUpdatedBy {get; set;}} public class Post: ITrackable {public int Id {get; set;} public string Title {get; set;} public string Content {get; set;} public DateTime CreatedAt {get; set;} public string CreatedBy {get; set;} public DateTime LastUpdatedAt {get; set } public string LastUpdatedBy {get; set;}}
Now we will change the default behavior of the SaveChanges method to set the value of the trace property. Be careful that there are two methods to override: the SaveChanges and the asynchronous method SaveChangesAsync. Traverses the entity tracked in the context in the code and sets the value of the tracking property based on the state. The code is very simple:
Public class BloggingContext: DbContext {public DbSet Posts {get; set;} public override int SaveChanges (bool acceptAllChangesOnSuccess) {OnBeforeSaving (); return base.SaveChanges (acceptAllChangesOnSuccess);} public override Task SaveChangesAsync (bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default (CancellationToken)) {OnBeforeSaving (); return base.SaveChangesAsync (acceptAllChangesOnSuccess, cancellationToken);} private void OnBeforeSaving () {var entries = ChangeTracker.Entries () Foreach (var entry in entries) {if (entry.Entity is ITrackable trackable) {var now = DateTime.UtcNow; var user = GetCurrentUser (); switch (entry.State) {case EntityState.Modified: trackable.LastUpdatedAt = now Trackable.LastUpdatedBy = user; break; case EntityState.Added: trackable.CreatedAt = now; trackable.CreatedAt = user; trackable.LastUpdatedAt = now; trackable.LastUpdatedBy = user Break;}} private string GetCurrentUser () {return "UserName"; / / TODO implement your own logic}}
There is a problem with this scenario that cannot be ignored. Properties are writable, and you do not want to set the value of the property in your code. Let's look at how to use the read-only property.
Read-only attribute
Entity Framework Core allows columns to be mapped to fields. This way, you can use the read-only property, and let's modify the Post class:
Public class Post {private DateTime _ createdAt; private string _ createdBy; private DateTime _ lastUpdatedAt; private string _ lastUpdatedBy; public int Id {get; set;} public string Title {get; set;} public string Content {get; set;} public DateTime CreatedAt = > _ createdAt; public string CreatedBy = > _ createdBy; public DateTime LastUpdatedAt = > _ lastUpdatedAt; public string LastUpdatedBy = > _ lastUpdatedBy;}
The above code is a bit troublesome, but the properties are now read-only. You need to instruct Entity Framework to use these fields to set the values of the column.
Public class BloggingContext: DbContext {public DbSet Posts {get; set;} protected override void OnModelCreating (ModelBuilder modelBuilder) {base.OnModelCreating (modelBuilder); modelBuilder.Entity () .Property (post = > post.CreatedAt) .HasField ("_ createdAt"); modelBuilder.Entity () .Property (post = > post.CreatedBy) .HasField ("_ createdBy") ModelBuilder.Entity () .property (post = > post.LastUpdatedAt) .HasField ("_ lastUpdatedAt"); modelBuilder.Entity () .Property (post = > post.LastUpdatedBy) .HasField ("_ lastUpdatedBy");}}
You cannot implement the OnBeforeSaving method as before, because the property does not have a setter. However, you can use ChangeTracker to instruct Entity Framework to set values for properties. There is no need to access properties or fields in this way.
Private void OnBeforeSaving () {var entries = ChangeTracker.Entries (); foreach (var entry in entries) {if (entry.Entity is Post post) {var now = DateTime.UtcNow; var user = GetCurrentUser () Switch (entry.State) {case EntityState.Modified: entry.CurrentValues ["LastUpdatedAt"] = now; entry.CurrentValues ["LastUpdatedBy"] = user; break Case EntityState.Added: entry.CurrentValues ["CreatedAt"] = now; entry.CurrentValues ["CreatedBy"] = user; entry.CurrentValues ["LastUpdatedAt"] = now; entry.CurrentValues ["LastUpdatedBy"] = user; break }}}
I think it should be the way to use it, because it is very clear.
Do not define attributes
In some cases, you may need to set the value of the column without defining properties in the model. For example, you might disclose the date of the last update, but not show who made the change. Entity Framework Core can handle this by using the Shadow attribute. The shadow property is declared in the OnModelCreating method, but does not exist in the class. You can use ChangeTracker to read and write the values of shadow properties.
Public class Post {public int Id {get; set;} public string Title {get; set;} public string Content {get; set;} public class BloggingContext: DbContext {protected override void OnModelCreating (ModelBuilder modelBuilder) {base.OnModelCreating (modelBuilder); / / Declare properties modelBuilder.Entity (). Property ("CreatedAt"); modelBuilder.Entity (). Property ("CreatedBy"); modelBuilder.Entity (). Property ("LastUpdatedAt") ModelBuilder.Entity (). Property ("LastUpdatedBy");} private void OnBeforeSaving () {var entries = ChangeTracker.Entries (); foreach (var entry in entries) {if (entry.Entity is Post post) {var now = DateTime.UtcNow; var user = GetCurrentUser () Switch (entry.State) {case EntityState.Modified: entry.CurrentValues ["LastUpdatedAt"] = now; entry.CurrentValues ["LastUpdatedBy"] = user; break Case EntityState.Added: entry.CurrentValues ["CreatedAt"] = now; entry.CurrentValues ["CreatedBy"] = user; entry.CurrentValues ["LastUpdatedAt"] = now; entry.CurrentValues ["LastUpdatedBy"] = user; break After reading this, the article "how to generate columns and track column records in Entity Framework Core" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it. If you want to know more about related articles, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.