0

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?

r3plica
  • 13,017
  • 23
  • 128
  • 290
  • 2
    by using `public int? CompanyId { get; set; }` ? (have you seen the **?**) – tschmit007 May 21 '15 at 12:01
  • 1
    Please start with nullable company id `public int? CompanyId { get; set; }` http://stackoverflow.com/questions/5668801/entity-framework-code-first-null-foreign-key – rraszewski May 21 '15 at 12:02

3 Answers3

0
public int? CompanyId { get; set; }

This will map CompanyId as nullable foreign key

PaulShovan
  • 2,140
  • 1
  • 13
  • 22
0

To add to the above answer: Nullable types are declared in one of two ways:

System.Nullable variable -or-

T? variable

T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.

The following MSDN link provides a good explanation https://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

perserver
  • 1
  • 4
0

Try this in your context class

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