简体   繁体   English

无法将ApplicationUser字段添加到通过EF Core创建的数据库中的多个记录中

[英]Unable to add ApplicationUser field to more than one record in database created through EF Core

My class Subcontractor has a property ApplicationUser CreatedUser. 我的类分包商有一个属性ApplicationUser CreatedUser。 When a subcontractor is created and added to the database I want to store the current IdentityUser as the CreatedUser. 创建分包商并将其添加到数据库后,我想将当前的IdentityUser存储为CreatedUser。 I used EF Core Migrations to create my database. 我使用EF Core Migrations创建了数据库。 The CreatedUser was mapped to CreatedUserId in the database as a foreign key by default when I added the migration. 添加迁移时,默认情况下,CreatedUser作为外键映射到数据库中的CreatedUserId。

When I run my app, the first subcontractor record that is added by a logged in user works fine and the CreatedUserId field is updated. 当我运行我的应用程序时,由登录用户添加的第一个分包商记录工作正常,并且CreatedUserId字段已更新。 My issue is that once a user tries to create a second subcontractor record I get an uncaught exception. 我的问题是,一旦用户尝试创建第二个分包商记录,我就会遇到未捕获的异常。 If I remove updating the CreatedUser field it works fine and I can add multiple subcontractor records. 如果删除更新CreatedUser字段,则可以正常工作,并且可以添加多个分包商记录。

This leads me to believe that I need to add my own relationship configuration in OnModelCreating to override the default EF migration configuration? 这使我相信我需要在OnModelCreating中添加自己的关系配置以覆盖默认的EF迁移配置? I am not sure though what I need to specify so that the Subcontractor database table will accept multiple records with the same CreatedUserId field? 我不确定是否需要指定什么以便分包商数据库表将接受具有相同CreatedUserId字段的多个记录? Or, is the default relationship correct, and do I need to change something in my create method to fix? 或者,默认关系是否正确,是否需要在我的create方法中进行某些更改以进行修复?

By default, this is what EF Core Migrations creates: 默认情况下,这是EF Core Migrations创建的内容:

modelBuilder.Entity("SubTracker.Data.Models.Subcontractor", b =>
{
   b.HasOne("SubTracker.Data.Models.ApplicationUser", "Approver")
       .WithMany()
       .HasForeignKey("ApproverId");

   b.HasOne("SubTracker.Data.Models.ApplicationUser", "CreatedUser")
        .WithMany()
        .HasForeignKey("CreatedUserId");
});

Paired down, my class is: 配对下来,我的课是:

 public class Subcontractor
 {
    public long Id { get; set; }
    public string Name { get; set; }
    public string AddressLineOne { get; set; }
    public string AddressLineTwo { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public ApplicationUser CreatedUser { get; set; }
}

In my controller my create method is: 在我的控制器中,我的创建方法是:

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,AddressLineOne,AddressLineTwo,City,State,Zipcode,ContactName,ContactEmail,ContactPhone")] Subcontractor subcontractor)
{
   if (ModelState.IsValid)
   {
     var user = await GetCurrentUserAsync();

     subcontractor.CreatedTimestamp = DateTime.Now;
     subcontractor.UpdatedTimestamp = subcontractor.CreatedTimestamp;
     subcontractor.AnnualSafetyPrequalApproved = false;
     subcontractor.AnnualInsuranceApproved = false;
     subcontractor.Status = "In Process";
     subcontractor.CreatedUser = user;

     _context.Add(subcontractor);

     await _context.SaveChangesAsync();

     return RedirectToAction(nameof(Index));
   }
   return View(subcontractor);
}

My ApplicationUser class: 我的ApplicationUser类:

public class ApplicationUser : IdentityUser
{
    public string Branch { get; set; }
    public string Area { get; set; }
    public string Title{ get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }        
    public string Role { get; set; }
 }

I have a separate DB context for Identity and for my application data. 对于身份和应用程序数据,我有单独的数据库上下文。 My paired down DBContext (removed other model classes but have nothing for ApplicationUser) for my application data is: 我配对的DBContext(删除了其他模型类,但对ApplicationUser则没有任何内容)是:

public class SubTrackerDbContext : DbContext
{
    public DbSet<Subcontractor> Subcontractors { get; set; }

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.ConfigureWarnings(warnings => warnings.Ignore(RelationalEventId.QueryClientEvaluationWarning));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Subcontractor>().ToTable("Subcontractor");        
    }
}

My DB context for Identity is: 我的身份数据库上下文是:

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

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

I think the problem is part of how you set the classes. 我认为问题是您如何设置课程的一部分。

First you need a foreign key for the ApplicationUser' in the Subcontractor` class: 首先,您需要ApplicationUser' in the Subcontractor`类中为ApplicationUser' in the使用外键:

public int CreatedUserId { get; set; }
public virtual ApplicationUser CreatedUser { get; set; }

Then (and this is optionally) your ApplicationUser must have a collection of Subcontractors : 然后(并且这是可选的),您的ApplicationUser必须具有Subcontractors的集合:

public virtual ICollection<Subcontractor> Subcontractors { get; set; }

On your create method just specify the user id not the entire user. 在您的create方法上,只需指定用户ID而不是整个用户即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 EF Core 中的不同项目之间向 ApplicationUser 添加外键? - How to add a foreign key to ApplicationUser between separate project in EF Core? 多个记录已更新EF-Linq C# - More than one record is updated EF-Linq C# 无法使用 EF Core 播种数据库 - Unable to seed database with EF Core EF Core Identity - 与返回 null 的另一个实体具有一对一关系的应用程序用户 - EF Core Identity - Applicationuser with one-to-one relationship with another entity returning null 使用 FluentValidation 访问验证多个字段的数据库 - Use FluentValidation to access the database validating more than one field EF Core LINQ GROUPBY 然后 Select 获取实体的多个属性 - EF Core LINQ GROUPBY Then Select to get more than one properties of the entity 当表具有多个外键时,EF Core 中的默认删除选项是什么? - What is default delete option in EF Core when a table have more than one foreign key? EF Core 3 的简单使用导致错误:序列包含多个匹配元素 - Simple usage of EF Core 3 results in error: Sequence contains more than one matching element 如何使用 EF Core fluent api 创建多个索引? - How to create more than one index using EF Core fluent api? 如何添加将通过多个类传递的属性 - How to add a property that will be passed through more than one class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM