Pio*_*nom 5 c# entity-framework ef-code-first
我有一些具有 CreatedDate 和/或 UpdatedDate 属性的模型,在我的播种中,我将它们设置为 DateTime.UtcNow。
new TestModel()
{
Id = 1,
Name = name,
CreatedDateUtc = DateTime.UtcNow,
CreatedBy = "Seed",
UpdatedDateUtc = DateTime.UtcNow,
UpdatedBy = "Seed",
DeletedDateUtc = null,
DeletedBy = null,
},
Run Code Online (Sandbox Code Playgroud)
现在,即使种子数据在数据库中,EF 认为它需要用新日期更新它们。这是预期的行为吗?我是否坚持为这些列指定日期?像这样的东西:
DateTime(2020, 01, 01, 12, 00, 00, DateTimeKind.Utc)
Run Code Online (Sandbox Code Playgroud)
每次运行种子方法时,它都会覆盖所有列,并且每次日期都不同。如果您想防止这种覆盖输入数据,那么您需要检查它是否已存在于您的数据库中,然后运行它。或者如果想阻止更新某些字段,则重写SaveChanges()中的方法。DbContext
例子:-
1.如果您不想更新输入数据那么--
protected override void Seed(ApplicationDbContext context)
{
if (!context.TestModels.Any(u => u.Id== 1))
{
context.TestModels.AddOrUpdate(p => p.Id, new TestModel()
{
Id = 1,
Name = "Test",
CreatedDateUtc = DateTime.UtcNow,
CreatedBy = "Seed",
UpdatedDateUtc = DateTime.UtcNow,
UpdatedBy = "Seed",
DeletedDateUtc = null,
DeletedBy = null,
});
}
base.Seed(context);
}
Run Code Online (Sandbox Code Playgroud)
2.如果想阻止更新某些字段(此过程适用于当前 DbContext 中任何位置的任何实体)--
属性 -
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public sealed class IgnoreUpdateAttribute : Attribute
{
}
Run Code Online (Sandbox Code Playgroud)
模型 -
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
[IgnoreUpdate]//for ignoring update
public DateTime CreatedDateUtc { get; set; }
[IgnoreUpdate]//for ignoring update
public string CreatedBy { get; set; }
public DateTime UpdatedDateUtc { get; set; }
public string UpdatedBy { get; set; }
public DateTime? DeletedDateUtc { get; set; }
public string DeletedBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
种子 -
protected override void Seed(ApplicationDbContext context)
{
context.TestModels.AddOrUpdate(p => p.Id, new TestModel()
{
Id = 1,
Name = "Test",
CreatedDateUtc = DateTime.UtcNow,
CreatedBy = "Seed",
UpdatedDateUtc = DateTime.UtcNow,
UpdatedBy = "Seed",
DeletedDateUtc = null,
DeletedBy = null,
});
base.Seed(context);
}
Run Code Online (Sandbox Code Playgroud)
数据库上下文--
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<TestModel> TestModels { get; set; }
//---DB Set
public override int SaveChanges()
{
var entities= ChangeTracker.Entries().Where(e => e.State == EntityState.Modified).ToList();
foreach (var entry in entities)
{
var properties = typeof(TestModel).GetProperties()// get you model properties
.Where(property =>
property != null && Attribute.IsDefined(property, typeof(IgnoreUpdateAttribute)))//which has decorated as IgnoreUpdate
.Select(p => p.Name);
foreach (var property in properties)
{
entry.Property(property).IsModified = false;
}
}
return base.SaveChanges();
}
//--- Code
}
Run Code Online (Sandbox Code Playgroud)
(已测试)
| 归档时间: |
|
| 查看次数: |
477 次 |
| 最近记录: |