尝试将记录插入到applicationuser引用的数据库中时出错

时间:2019-11-05 10:26:12

标签: c# asp.net-core asp.net-identity asp.net-core-webapi

我有以下一对多关系:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Company { get; set; }
    public virtual ICollection<GSMSite> GSMSites { get; set; }
}

public class GSMSite
{
    public int Id { get; set; }
    public string SiteName { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string Town { get; set; }
    public string Postcode { get; set; }
    public string ContactName { get; set; }
    public string ContactNumber { get; set; }
    public string ContactEmail { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

构建器配置:

      builder.Entity<ApplicationUser>()
               .HasMany(c => c.GSMSites)
               .WithOne(e => e.ApplicationUser)
               .IsRequired();

控制器:

  [Route("createsite")]
    [HttpPost]
    public async Task<IActionResult> CreateSite(GSMSite site)
    {
        var user = await _userManager.FindByIdAsync(HttpContext.GetUserId().ToString());

        var GSMSite = new GSMSite
        {
            SiteName = site.SiteName,
            AddressLine1 = site.AddressLine1,
            AddressLine2 = site.AddressLine2,
            Town = site.Town,
            Postcode = site.Postcode,
            ContactName = site.ContactName,
            ContactNumber = site.ContactNumber,
            ContactEmail = site.ContactEmail,
            ApplicationUser = user
        };

        await _gSMSitesServices.CreateSiteAsync(site);

        return Ok();

    }

我可以很好地添加用户,尽管在尝试添加GSMSite时出现以下错误。我已经检查了用户,它确实包含当前用户,有什么想法吗?

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ApplicationUserID', table 'videxbui_app.dbo.GSMSite'; column does not allow nulls. INSERT fails.
The statement has been terminated.

0 个答案:

没有答案