【发布时间】:2019-07-01 22:00:13
【问题描述】:
我得到错误'运算符'=='不能应用于'string'和'int'类型的操作数?在这条线上
.FirstOrDefaultAsync(m => m.Id == id);
到目前为止,除了这个方法,我还没有尝试过任何其他方法。
public class EditProfileController : Controller
{
private readonly ApplicationDbContext db;
private object _context;
public EditProfileController(ApplicationDbContext Db)
{
db = Db;
}
public IActionResult Index()
{
List<ApplicationUser> listdata = db.Users
.Select(user => new ApplicationUser()
{
Id = user.Id,
UserName = user.UserName,
NormalizedUserName = user.NormalizedUserName,
Email = user.Email
// Add the remainder properties
}).ToList();
return View(listdata);
}
[HttpGet]
public ActionResult Edit(string id)
{
//Get user and return the Edit View
ApplicationUser user = db.Users.Where(u => u.Id == id)
.Select(u => new ApplicationUser()
{
Id = u.Id,
UserName = u.UserName,
NormalizedUserName = u.NormalizedUserName,
Email = u.Email
// Add the remainder properties
}).FirstOrDefault();
return View(user);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicationUser listdata)
{
if (ModelState.IsValid)
{
db.Entry(listdata).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(listdata);
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var user = await db.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (user == null)
{
return NotFound();
}
return View(user);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var user = await db.Users.FindAsync(id);
db.Users.Remove(user);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
我的预期结果是,当我单击视图页面上的删除链接时,它要求确认删除,然后一旦我单击是或否,它就会执行 DeleteConfirmed 操作。我需要什么来修复这个错误?
【问题讨论】:
-
错误很明显,说明代码有问题。
id是字符串还是整数?不可能两者兼而有之。使用正确的类型。 -
IdentityUser的默认主键列类型是字符串,而不是 int。如果您愿意,可以将其 make 设为 int,但这不是默认设置。此外,FWIW,您应该始终使用UserManager<TUser>管理用户,而不是直接使用上下文。在创建用户时,它会在幕后做很多事情,你的应用程序代码不应该关心自己(例如规范化用户名和电子邮件)。您可以通过上下文选择用户,但标准 CRUD 应该通过管理器进行。