gpt4 book ai didi

c# - 如何将计算值添加到此 TryUpdateModelAsync<>

转载 作者:行者123 更新时间:2023-11-30 12:20:07 30 4
gpt4 key购买 nike

我有以下代码:

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 的属性:LastDateModifiedLastModified 这是计算/预定义的值

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");
}
// ...
}

请注意 LastModifiedLastDateModifiedBy 不是 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com