【问题标题】:How to save ApplicationUser as a foreign key in another table如何将 ApplicationUser 保存为另一个表中的外键
【发布时间】:2021-07-05 11:06:27
【问题描述】:

如何将 ApplicationUser 保存为另一个表中的外键

using Microsoft.AspNetCore.Identity;

namespace APP.Models
{
    public class AppUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Operador Document{ get; set; }
    }
}

using Microsoft.AspNetCore.Identity;

namespace APP.Models
{
    public class Document
    {
        public int ID { get; set; }
        public string DESC{ get; set; }
        public string SLUG{ get; set; }
        [ForeignKey("UserID")]
        public AppUser AppUser { get; set; }
    }
}

建立关联时:

AppUser user = await _userManager.FindByEmailAsync("test@local.local");

Document doc = new Document();
doc.ID = 1;
doc.DESC= "DESC1";
doc.SLUG= "SLUG1";
doc.UserId = user;

但是当我尝试保存它时出现错误:

Cannot insert explicit value for identity column in table 'Document' when IDENTITY_INSERT is set to OFF.

有人可以帮助我吗? 谢谢

【问题讨论】:

    标签: asp.net-mvc asp.net-core asp.net-identity


    【解决方案1】:

    您正在向 Identity 列插入一个值。如果您想通过密钥保存 Id,则应在 Document Table 上启用 IDENTITY_INSERT

    通过执行此sql 查询,您将在Document 表上将IDENTITY_INSERT 设置为ON

    SET IDENTITY_INSERT Document ON
    

    另一种选择是删除您的密钥。

    AppUser user = await _userManager.FindByEmailAsync("test@local.local");
    
    Document doc = new Document();
    doc.DESC= "DESC1";
    doc.SLUG= "SLUG1";
    doc.UserId = user;
    

    此时SQL自动生成的Document表的Id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多