第一个可空的外键

本文关键字:第一个 | 更新日期: 2023-09-27 17:50:19

所有,

我试图得到一个可空的外键,但不能得到这个为我工作。我的模型是这样的:

public class User : IdentityUser
{
    public string Telephone { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime LastLoginDate { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public string CreatedById { get; set; }
    public string ModifiedById { get; set; }
    public User CreatedBy { get; set; }
    public User ModifiedBy { get; set; }
    public bool Deleted { get; set; }
    public int CompanyId { get; set; }
    /// <summary>
    /// Generate the user identity
    /// </summary>
    /// <param name="service">The user service</param>
    /// <param name="authenticationType">The autentication type</param>
    /// <returns></returns>
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserService service, string authenticationType)
    {
        // Create our identity
        var userIdentity = await service.CreateIdentityAsync(this, authenticationType);
        // Return our identity
        return userIdentity;
    }
}
CompanyId是应该为空的外键,所以在我的DbContext中我设置了这个映射:
modelBuilder.Entity<Company>().HasMany(m => m.Members).WithOptional().HasForeignKey(m => m.CompanyId);

但是当我运行我的应用程序时,我总是得到一个错误:

  • InnerException {" INSERT语句与外键约束冲突'" fk_dbo . users_dbo . companyies_companyid '"。冲突发生在数据库"melanite",表"dbo"中。Companies'",列"Id"。'r'n语句已终止。"}系统。异常{System.Data.SqlClient.SqlException}

有谁知道我如何才能改变我的映射正确工作?

第一个可空的外键

public int? CompanyId { get; set; }

这将把CompanyId映射为可空外键

对上述答案进行补充:可空类型以以下两种方式之一声明:

系统。可空变量————

T ?变量

T是可空类型的基础类型。T可以是任何值类型,包括struct;不能是引用类型

下面的MSDN链接提供了很好的解释https://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

在您的上下文类中试试

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                .HasOptional(s => s.Company);}