从 Model .net 核心引用 ApplicationUser
Referencing ApplicationUser from Model .net core
我正在做一个项目,我有两个对象 Group
和 ApplicationUser
以及从 Group
到 ApplicationUser
的引用。我的 Group
模型有一个 属性 CreatedBy
来提供有关创建组的用户的信息。
正确执行保存组,CreatedBy
属性将userId存储在数据库中。当我想显示组(对象)列表时会发生此问题。 CreatedBy
属性 未被检索,而是具有空值(尽管已保存 userId 值)。
群模型:
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string Descriotion { get; set; }
public ApplicationUser CreatedBy { get; set; }
}
组控制器(有保存和显示方法):
public class GroupController : Controller
{
private readonly ApplicationDbContext _db;
private readonly UserManager<IdentityUser> _userManager;
public GroupController(ApplicationDbContext db, UserManager<IdentityUser> userManager)
{
_db = db;
_userManager = userManager;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Descriotion")] Group @group)
{
string userId = _userManager.GetUserId(User);
var appUser = _db.ApplicationUser.Find(userId);
if (!String.IsNullOrEmpty(userId) && appUser != null)
{
group.CreatedBy = appUser;
}
if (ModelState.IsValid)
{
_db.Add(@group);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(@group);
}
public async Task<IActionResult> Groups()
{
return View("Groups", await _db.Groups.ToListAsync());
}
}
应用程序用户模型:
public class ApplicationUser : IdentityUser
{
[NotMapped]
public string RoleId { get; set; }
[NotMapped]
public string Role { get; set; }
public ApplicationUser()
{
}
}
组迁移(模型):
public partial class GroupsModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Groups",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: true),
Descriotion = table.Column<string>(type: "text", nullable: true),
CreatedById = table.Column<string>(type: "text", nullable: false),
},
constraints: table =>
{
table.PrimaryKey("PK_Groups", x => x.Id);
table.ForeignKey(
name: "FK_Groups_AspNetUsers_CreatedById",
column: x => x.CreatedById,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Groups_CreatedById",
table: "Groups",
column: "CreatedById");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Groups");
}
}
我的上下文文件
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<Group> Groups { get; set; }
}
1.我的模型或任何其他文件有问题吗?如何检索具有 CreatedBy
正确值的组对象?
2。有没有更好的方法设置CreatedBy
属性
现在我需要创建 ApplicationUser
对象,以便设置 属性。
有没有办法只提供 userId(字符串)而不创建 ApplicationUser
?
string userId = _userManager.GetUserId(User);
var appUser = _db.ApplicationUser.Find(userId);
if (!String.IsNullOrEmpty(userId) && appUser != null)
{
group.CreatedBy = appUser;
}
如果你想看到它,你必须包括用户
public async Task<IActionResult> Groups()
{
return View("Groups", await _db.Groups.Include(i=>i.CreatedBy).ToListAsync());
}
EF Net 5+ 可以隐含地创建外键列,但是将外键显式地包含到 class 始终是个好主意
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string Descriotion { get; set; }
public string CreatedById { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
}
这样你的代码会更简单
string userId = _userManager.GetUserId(User);
if ( !string.IsNullOrEmpty(userId)) group.CreatedById = userId;
我正在做一个项目,我有两个对象 Group
和 ApplicationUser
以及从 Group
到 ApplicationUser
的引用。我的 Group
模型有一个 属性 CreatedBy
来提供有关创建组的用户的信息。
正确执行保存组,CreatedBy
属性将userId存储在数据库中。当我想显示组(对象)列表时会发生此问题。 CreatedBy
属性 未被检索,而是具有空值(尽管已保存 userId 值)。
群模型:
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string Descriotion { get; set; }
public ApplicationUser CreatedBy { get; set; }
}
组控制器(有保存和显示方法):
public class GroupController : Controller
{
private readonly ApplicationDbContext _db;
private readonly UserManager<IdentityUser> _userManager;
public GroupController(ApplicationDbContext db, UserManager<IdentityUser> userManager)
{
_db = db;
_userManager = userManager;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Descriotion")] Group @group)
{
string userId = _userManager.GetUserId(User);
var appUser = _db.ApplicationUser.Find(userId);
if (!String.IsNullOrEmpty(userId) && appUser != null)
{
group.CreatedBy = appUser;
}
if (ModelState.IsValid)
{
_db.Add(@group);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(@group);
}
public async Task<IActionResult> Groups()
{
return View("Groups", await _db.Groups.ToListAsync());
}
}
应用程序用户模型:
public class ApplicationUser : IdentityUser
{
[NotMapped]
public string RoleId { get; set; }
[NotMapped]
public string Role { get; set; }
public ApplicationUser()
{
}
}
组迁移(模型):
public partial class GroupsModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Groups",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: true),
Descriotion = table.Column<string>(type: "text", nullable: true),
CreatedById = table.Column<string>(type: "text", nullable: false),
},
constraints: table =>
{
table.PrimaryKey("PK_Groups", x => x.Id);
table.ForeignKey(
name: "FK_Groups_AspNetUsers_CreatedById",
column: x => x.CreatedById,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Groups_CreatedById",
table: "Groups",
column: "CreatedById");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Groups");
}
}
我的上下文文件
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<Group> Groups { get; set; }
}
1.我的模型或任何其他文件有问题吗?如何检索具有 CreatedBy
正确值的组对象?
2。有没有更好的方法设置CreatedBy
属性
现在我需要创建 ApplicationUser
对象,以便设置 属性。
有没有办法只提供 userId(字符串)而不创建 ApplicationUser
?
string userId = _userManager.GetUserId(User);
var appUser = _db.ApplicationUser.Find(userId);
if (!String.IsNullOrEmpty(userId) && appUser != null)
{
group.CreatedBy = appUser;
}
如果你想看到它,你必须包括用户
public async Task<IActionResult> Groups()
{
return View("Groups", await _db.Groups.Include(i=>i.CreatedBy).ToListAsync());
}
EF Net 5+ 可以隐含地创建外键列,但是将外键显式地包含到 class 始终是个好主意
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string Descriotion { get; set; }
public string CreatedById { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
}
这样你的代码会更简单
string userId = _userManager.GetUserId(User);
if ( !string.IsNullOrEmpty(userId)) group.CreatedById = userId;