C# 如何在ASP.NET MVC中将IdentityUser与Recipe连接
我想在ASP.NET.CORE MVC中,在IdentityUser和Recipe之间创建一对多关系。当我尝试将ApplicationSerID分配给当前登录的用户ID时,它会得到空值。在服务器资源管理器中打开AspNetUsers时,它没有Recipes属性。我不知道如何使它正常工作 ApplicationUser.csC# 如何在ASP.NET MVC中将IdentityUser与Recipe连接,c#,entity-framework,asp.net-core-mvc,one-to-many,C#,Entity Framework,Asp.net Core Mvc,One To Many,我想在ASP.NET.CORE MVC中,在IdentityUser和Recipe之间创建一对多关系。当我尝试将ApplicationSerID分配给当前登录的用户ID时,它会得到空值。在服务器资源管理器中打开AspNetUsers时,它没有Recipes属性。我不知道如何使它正常工作 ApplicationUser.cs namespace WebApplication.Models { public class ApplicationUser : IdentityU
namespace WebApplication.Models
{
public class ApplicationUser : IdentityUser
{
public List<Recipe> Recipes { get; set; }
}
}
namespace WebApplication.Controllers
{
public class RecipeController : Controller
{
private readonly ApplicationDbContext _applicationDbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public RecipeController( ApplicationDbContext applicationDbContext, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
_applicationDbContext = applicationDbContext;
_userManager = userManager;
}
public IActionResult Create()
{
var userId = _userManager.GetUserId(User);
return View();
}
[HttpPost]
public async Task<IActionResult> Create([Bind("RecipeName,RecipeContent")] Recipe recipe)
{
var userId = _userManager.GetUserId(User);
recipe.ApplicationUserId = userId;
_applicationDbContext.Recipes.Add(recipe);
await _applicationDbContext.SaveChangesAsync();
return View(recipe);
}
}
}
namespace WebApplication.Models
{
public class Recipe
{
[Key]
public Guid Id { get; set; }
[Required]
public string RecipeName { get; set; }
[Required]
public string RecipeContent { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
}
namespace WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Startup.cs
namespace WebApplication.Models
{
public class ApplicationUser : IdentityUser
{
public List<Recipe> Recipes { get; set; }
}
}
namespace WebApplication.Controllers
{
public class RecipeController : Controller
{
private readonly ApplicationDbContext _applicationDbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public RecipeController( ApplicationDbContext applicationDbContext, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
_applicationDbContext = applicationDbContext;
_userManager = userManager;
}
public IActionResult Create()
{
var userId = _userManager.GetUserId(User);
return View();
}
[HttpPost]
public async Task<IActionResult> Create([Bind("RecipeName,RecipeContent")] Recipe recipe)
{
var userId = _userManager.GetUserId(User);
recipe.ApplicationUserId = userId;
_applicationDbContext.Recipes.Add(recipe);
await _applicationDbContext.SaveChangesAsync();
return View(recipe);
}
}
}
namespace WebApplication.Models
{
public class Recipe
{
[Key]
public Guid Id { get; set; }
[Required]
public string RecipeName { get; set; }
[Required]
public string RecipeContent { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
}
namespace WebApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
命名空间Web应用程序
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddControllersWithViews();
services.AddDbContext也许这对您有用。
在Sql Server中,执行以下命令
ALTER TABLE Recipes
ADD UserId nvarchar(450)
ALTER TABLE Recipes
ADD FOREIGN KEY (UserId) REFERENCES AspNetUsers(Id)
你有没有遵循官方文件
您是否更新了ApplicationDbCOntext类以从IdentityDbContext派生
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public virtual DbSet<Recipe> Recipes { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
更新1:
我明白你的意思了,它没有用外键创建字段。我在其中创建了一个外键,但在初始创建时它没有创建另一个表。也许这会对你有所帮助
public class ApplicationUser : IdentityUser
{
public virtual Recipe Recipes { get; set; }
}
回答你自己的问题,如果你找到了解决方案,我或多或少也面临着同样的问题,如果我找到了解决方案,我会继续调查并更新我的帖子
好的,它与我上面更新的内容一起工作。我有屏幕截图确认。我让它在我的数据库上工作。让我知道它是否对您有效。当您说“[…]当前登录的userId它得到null值”时,您的意思是var userId=\u userManager.GetUserId(User);
为空?如果是,您是使用cookie身份验证还是如何识别用户?请共享您的启动。csI已添加启动。csI是否尝试在您的创建
路由上添加[Authorize]
属性?您好@KamilGórny,哪个值为空?