自动生成属性值是指在添加或更新实体时由 EF 或数据库自动生成字段的值。
public class Blog { public DateTime CreateDate { get; set; } public DateTime? UpdateDate { get; set; } }
在添加期间保存显式值
默认值方案
//modelBuilder.Entity<Blog>() .Property(b => b.CreateDate) .HasDefaultValue(DateTime.Now); modelBuilder.Entity<Blog>() .Property(b => b.CreateDate) .HasDefaultValueSql("GETDATE()");
显式值插入 SQL Server IDENTITY 列
按照约定,主键会自动生成自增列。对于大多数情况,这样是适用的。
但是,若要将显式值插入到 SQL Server IDENTITY 列中 (比如:导数据),则必须在调用 SaveChanges() 之前手动启用 IDENTITY_INSERT 特性。
using (var context = new BloggingContext()) { var blog1 = new Blog { BlogId = 33, Name = "zerodo1", Url = "www.xcode1.me", }; var blog2 = new Blog { BlogId = 44, Name = "zerodo2", Url = "www.xcode2.me", }; _context.Add(blog1); _context.Add(blog2); _context.Database.OpenConnection(); try { _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [Blogs] ON"); await _context.SaveChangesAsync(); _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [Blogs] OFF"); } finally { _context.Database.CloseConnection(); } }
在更新期间设置显式值
modelBuilder.Entity<Blog>().Property(b => b.UpdateDate).ValueGeneratedOnAddOrUpdate(); modelBuilder.Entity<Blog>().Property(b => b.UpdateDate).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
CREATE TRIGGER [dbo].[Blogs_UPDATE] ON [dbo].[Blogs] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN; DECLARE @Id INT SELECT @Id = INSERTED.BlogId FROM INSERTED UPDATE dbo.Blogs SET UpdateDate = GETDATE() WHERE BlogId = @Id END