簡體   English   中英

如何將Identity dbcontext與應用程序上下文合並?

[英]How to merge Identity dbcontext with application context?

我無法從“應用程序標識用戶”中讀取數據。 我是新手,有什么主意嗎? 編譯時沒有錯誤。 但是我無法添加新任務。

創建任務https:// localhost:44312 / usertasks / Create時出現錯誤

問題在GET方法上,但用戶lis不為空

  • 結果視圖展開結果視圖將枚舉IEnumerable
  • [0] {lukas@wp.pl} UserTaskTest.Models.ApplicationUser AccessFailedCount 0 int ConcurrencyStamp“ 785f9a54-e7f1-4e3b-8bad-55165155d631”字符串電子郵件“ lukas@wp.pl”字符串EmailConfirmed false bool ExecutedUserTasks null System.Collections.Generic .ICollection ID“ 53f416ab-aa1e-465f-9dd4-dc32e11914ae”字符串LockoutEnabled true bool LockoutEnd null System.DateTimeOffset? NormalizedEmail “LUKAS@WP.PL” 字符串NormalizedUserName “LUKAS@WP.PL” 串OwnedUserTasks空了System.Collections.Generic.ICollection PasswordHash “AQAAAAEAACcQAAAAEIqkXlzky + 4i8BsPl5Z4524B3Dj3u0RZMY2Rf5ch5l22GEMj5m0LsVgeWDAavmVO + G ==” 字符串******中國空字符串PhoneNumberConfirmed假布爾SecurityStamp“698529ad-c47c- 40f9-bdf3-c4d946cda86a“字符串TwoFactorEnabled false bool UserName” lukas@wp.pl“字符串
  • [1] {li@wp.pl} UserTaskTest.Models.ApplicationUser AccessFailedCount 0 int ConcurrencyStamp“ 1a9064e2-3cc9-4794-9198-81423a5d8cd2”字符串電子郵件“ li@wp.pl”字符串EmailConfirmed false bool ExecutedUserTasks null System.Collections.Generic .ICollection ID“ 970839dc-31be-4966-8f06-e664aca3622c”字符串LockoutEnabled true bool LockoutEnd null System.DateTimeOffset? NormalizedEmail “LI@WP.PL” 字符串NormalizedUserName “LI@WP.PL” 串OwnedUserTasks空了System.Collections.Generic.ICollection PasswordHash “AQAAAAEAACcQAAAAEM2KiwEfRDomBNiWXHmEtvwWEodfZDb8eaSADOGP2ZralzlnBDZEMQIsOvTk1nHMcw ==” 字符串******中國空字符串PhoneNumberConfirmed假布爾SecurityStamp“0a829111-88d7-4a8a-b65d- 5582cecbe67f“字符串TwoFactorEnabled false bool UserName” li@wp.pl“字符串

System.NullReferenceException:對象引用未設置為對象的實例。

Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField()
在Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItems()
在Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator()

public class UserTask
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserTaskID { get; set; }

    public string Description { get; set; }

    [ForeignKey("OwnerUserID")]
    public string TaskOwnerId { get; set; }

    [ForeignKey("ExecutorUserID")]
    public string TaskExecutorId { get; set; }

    public virtual ApplicationUser OwnerUserID { get; set; }
    public virtual ApplicationUser ExecutorUserID { get; set; }

}


public class ApplicationUser : IdentityUser
{
     public ICollection<UserTask> OwnedUserTasks { get; set; }
     public ICollection<UserTask> ExecutedUserTasks { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<UserTask> UserTask { get; set; }


    protected override void OnModelCreating(ModelBuilder builder)
    {
       base.OnModelCreating(builder);

       builder.Entity<ApplicationUser>()
           .HasMany(x => x.OwnedUserTasks)
           .WithOne(x => x.OwnerUserID);

       builder.Entity<ApplicationUser>()
           .HasMany(x => x.ExecutedUserTasks)
           .WithOne(x => x.ExecutorUserID);
    }
}

啟動文件

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }
}

UserTaskControler

public class UserTasksController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;

    public UserTasksController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    public IActionResult Create()
    {
        ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

        ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

        return View();
    }
}

和視圖

@model UserTaskTest.Models.UserTask

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<h4>UserTask</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TaskOwnerId" class="control-label"></label>
                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>
            </div>
            <div class="form-group">
             <!--   <label asp-for="TaskExecutorId" class="control-label"></label>
                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select> -->
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

_userManager導致了此問題。 假定由於更改跟蹤和ForeignKeys的性質,您試圖更改User 嘗試用_dbContext.Users.ToList()填充您的下拉_dbContext.Users.ToList() ,盡管在生成的上下文中它不顯示可用,但這是繼承禮物。

除非您在ApplicationUser中實際創建了屬性,否則下拉列表中的Name也會出錯,因為默認情況下該屬性不存在。 https://github.com/aspnet/Identity/blob/dev/src/Microsoft.Extensions.Identity.Stores/IdentityUser.cs

public class ApplicationUser : IdentityUser
{
   public string Name {get;set;}  //?? missing?

   public ICollection<UserTask> OwnedUserTasks { get; set; }
   public ICollection<UserTask> ExecutedUserTasks { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM