各位大大好:
想請教asp net問題,目前使用visual studio 2022,我有在aspnetusers的資料表新增一個MyID的欄位
註冊的時候確實是可以把資料寫進去
但是在讀的時候就是讀不到MyID的欄位,我只能讀到asp他預設的欄位....
以下是程式碼:
ApplicationUser.cs//我新增的欄位
public class ApplicationUser : IdentityUser
{
public string MyId { get; set; }
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{ >
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new ApplicationUserEntityConfiguration());
}
private class ApplicationUserEntityConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.Property(u=>u.MyId).HasMaxLength(50);
}
}
public DbSet<ApplicationUser>? ApplicationUsers { get; set; }
}
MyControl.cs
public class MyController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ApplicationUser _users;
public EvidencesController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
var curUserId=User.FindFirstValue(ClaimTypes.Name);
var tmp = _context.Users.Where(u => u.UserName == curUserId).FirstOrDefault();
ViewBag.MyId = tmp.MyId;//這裡會錯誤,找不到MyId,可是欄位明明就有新增阿....
return View();
}
}
}
謝謝各位
你讀資料應該是用ApplicationDbContext,
ApplicationDbContext裡面有這個欄位嗎?
我ApplicationDbContext的程式碼有放在上面喔
MyId有放裡面
private class ApplicationUserEntityConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.Property(u=>u.MyId).HasMaxLength(50);//這裡
}
}
public DbSet<ApplicationUser>? ApplicationUsers { get; set; }
這樣是OK的嗎?還是要用其他方法?
我已經解決了,program.cs也需要改才行,謝謝