- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码:
if (await TryUpdateModelAsync<Host>(
hostToUpdate,
"Host",
s => s.Name, s => s.Description, s => s.Address, s => s.Postcode, s => s.Suburb,
s => s.State))
{
try
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (Host)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, "Unable to save. " +
"The host was deleted by another user.");
return Page();
}
var dbValues = (Host)databaseEntry.ToObject();
await setDbErrorMessage(dbValues, clientValues, _context);
// Save the current RowVersion so next postback
// matches unless an new concurrency issue happens.
Host.RowVersion = (byte[])dbValues.RowVersion;
// Must clear the model error for the next postback.
ModelState.Remove("Host.RowVersion");
}
}
我有一个名为 Host 的属性:LastDateModified
和 LastModified
这是计算/预定义的值
即 DateTime.Now
用于 LastDateModified
和 _userManager.GetUserId(User)
用于 LastDateModifiedBy
。
那么如何将其传递到这段代码中呢?
await TryUpdateModelAsync<Host>(
hostToUpdate,
"Host",
s => s.Name, s => s.Description, s => s.Address, s => s.Postcode, s => s.Suburb,
s => s.State)
最佳答案
您可以在保存对象之前设置(替代)值:
var hostToUpdate = await _context.Host.FindAsync(s => s.Id == id);
if (await TryUpdateModelAsync(
hostToUpdate,
"host", // empty with MVC
s => s.Name, s => s.Description, s => s.Address,
s => s.Postcode, s => s.Suburb, s => s.State))
{
try
{
hostToUpdate.LastModified = DateTime.Now;
hostToUpdate.LastDateModifiedBy = _userManager.GetUserId(User);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
// ...
}
请注意 LastModified
和 LastDateModifiedBy
不是 TryUpdateModelAsync
语句的一部分。但如果是,这些值将被操作覆盖。
来自 Razor 页面 documentation :
The DB context keeps track of whether entities in memory are in sync with their corresponding rows in the DB. The DB context sync information determines what happens when SaveChangesAsync is called.
来自 Mvc documentation (不再更新):
The Entity Framework's automatic change tracking sets the Modified flag on the fields that are changed by form input. When the SaveChanges method is called, the Entity Framework creates SQL statements to update the database row.
为解释其工作原理,首先 TryUpdateModelAsync 更新用户更新的字段,然后该操作更新其他字段。所有这些都由 Entity Framework 进行跟踪和保存。这是 Entity Framework 的默认行为。
作为旁注,您的替代方法是添加自动更新字段的代码。在那种情况下,您不能忘记设置它们并保存几行代码。而且您根本不需要更改代码。
该策略是实体实现基字段并在保存更改时更新它们。这是一个更扩展的版本:
public interface IBaseEntity
{
DateTime LastDateModified { get; set; }
string LastDateModifiedBy { get; set; }
DateTime DateCreated { get; set; }
string DateCreatedBy { get; set; }
}
public class Host : IBaseEntity
{
// the other fields
// ...
public DateTime LastDateModified { get; set; }
public string LastDateModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public string DateCreatedBy { get; set; }
}
上下文:
public partial class MyContext : DbContext
{
// Reference to the name of the current user.
private readonly string _userName;
public MyContext(DbContextOptions<MyContext> options, IHttpContextAccessor httpContext)
: base(options)
{
// Save the name of the current user so MyContext knows
// who it is. The advantage is that you won't need to lookup
// the User on each save changes.
_userName = httpContext.HttpContext.User.Identity.Name;
}
public virtual DbSet<Host> Host { get; set; }
// You'll only need to override this, unless you are
// also using non-async SaveChanges.
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
UpdateEntries();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
// You can move this to another partial class.
private void UpdateEntries()
{
// Modified
var modified = ChangeTracker.Entries().Where(v => v.State == EntityState.Modified && typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();
modified.ForEach(entry =>
{
((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
((IBaseEntity)entry.Entity).LastDateModifiedBy = _userName;
});
// Added
var added = ChangeTracker.Entries().Where(v => v.State == EntityState.Added && typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();
added.ForEach(entry =>
{
((IBaseEntity)entry.Entity).DateCreated = DateTime.UtcNow;
((IBaseEntity)entry.Entity).DateCreatedBy = _userName;
((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
((IBaseEntity)entry.Entity).LastDateModifiedBy = _userName;
});
}
// ...
}
在启动中添加HttpContextAccessor:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
现在每次保存实现 IBaseEntity 的对象时,字段都会自动更新。
请注意,我没有在此处注入(inject) UserManager。如果用户包含名称声明,那么您可以改用它。这将保存对数据库的调用。
作为一项改进,您可以编写一个新服务来负责解析用户名并将其注入(inject)。
关于c# - 如何将计算值添加到此 TryUpdateModelAsync<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293634/
我有一个 TryUpdateModelAsync 调用,一旦失败,只会返回 false。目前还不清楚它失败的原因。我怎样才能获得更多信息? if (await TryUpdateModelAsync(
我有一个 TryUpdateModelAsync 调用,一旦失败,只会返回 false。目前还不清楚它失败的原因。我怎样才能获得更多信息? if (await TryUpdateModelAsync(
我用这样的模型绑定(bind)更新我的数据库: var adminUpdate = await _context.Admins.FindAsync(Id); if (!String.IsNullOrE
我有以下代码: if (await TryUpdateModelAsync( hostToUpdate, "Host",
所以我正在这样做 microsoft tutorial在带有 EF 6 的 ASP.NET Core 上,它刚刚通过编辑 Controller 更新了一个模型。 这段代码让我非常困惑,我想(也许希望)
假设我有一个包含以下模型结构的表单: TestRecord.cs class TestRecord { public string Id { get; set; } public st
TryUpdateModelAsync 是抽象类 PageModel 的一个内部保护方法,在我看来,这使得它不可模拟。是否有任何方法可以对涉及此方法的任何操作进行单元测试? 我在网上看到这个解决方案:
我是一名优秀的程序员,十分优秀!