r3plica r3plica - 2 months ago 16
C# Question

EntityFramework Code First nullable foreign key

I all,

I am trying to get a nullable foreign key but can not get this to work for me.
My model looks like this:

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;

The CompanyId is the foreign key that should be null, so in my DbContext I have set this mapping:

modelBuilder.Entity<Company>().HasMany(m => m.Members).WithOptional().HasForeignKey(m => m.CompanyId);

But when I run my application I always get an error:

  • InnerException {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Users_dbo.Companies_CompanyId\". The conflict occurred in database \"melanite\", table \"dbo.Companies\", column 'Id'.\r\nThe statement has been terminated."} System.Exception {System.Data.SqlClient.SqlException}

does anyone know how I can change my mapping to work correctly?

public int? CompanyId { get; set; }

This will map CompanyId as nullable foreign key