关系需要以下步骤:
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public ICollection<User> Users { get; set; }
}
public class YourDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.UsingEntity(j => j.ToTable("UserRole"));
}
}
[Route("api/users")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly YourDbContext _context;
public UsersController(YourDbContext context)
{
_context = context;
}
[HttpGet("{userId}/roles")]
public IActionResult GetUserRoles(int userId)
{
var user = _context.Users.Include(u => u.Roles).FirstOrDefault(u => u.UserId == userId);
if (user == null)
{
return NotFound();
}
return Ok(user.Roles);
}
[HttpGet("{roleId}/users")]
public IActionResult GetRoleUsers(int roleId)
{
var role = _context.Roles.Include(r => r.Users).FirstOrDefault(r => r.RoleId == roleId);
if (role == null)
{
return NotFound();
}
return Ok(role.Users);
}
}
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnectionString")));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
这样,当你发送GET请求到/api/users/{userId}/roles,将会返回指定用户的角色列表;而发送GET请求到/api/roles/{roleId}/users,则会返回指定角色的用户列表。
在这个示例中,我没有提及任何腾讯云相关产品,因为与问题本身的要求一致。你可以根据实际需要选择适合的云计算产品来托管ASP.net应用程序,并进行相应的配置和部署。
领取专属 10元无门槛券
手把手带您无忧上云