Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Sql Error: Invalid column name 'PrimaryContact_ContactID'

Will someone please put me out of my misery and let me know what I have/have not done that makes my code fail?

I am using Entity Framework database first. When I query for an entity and request a related entity to be included, I get this error: Invalid column name 'PrimaryContact_ContactID'. The exception is thrown on the line with the call to the Load method.

I am trying to query one of the Enterprise entities and have it include the Company entity as well.

(This is a simplified example that duplicates the exception)

Here are my entity classes:

//Enterprise
public class Enterprise
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyID { get; set; }

    public virtual Company Company { get; set; }
}

//Company
public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PrimaryContactId { get; set; }

    public virtual CompanyContact PrimaryContact { get; set; }
}

//CompanyContact class
public class CompanyContact
{
    public int ContactID { get; set; }
    public string Name { get; set; }
}

Here is the DataContext class

public class DataContext : DbContext
{
    public DbSet<Enterprise> Enterprises { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<CompanyContact> CompanyContacts { get; set; }

    public DataContext(string connStrName = nameof(DataContext)) : base($"Name={connStrName}")
    {
        Database.SetInitializer<DataContext>(null);
        base.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Enterprise>().HasKey(pk => pk.Id);
        modelBuilder.Entity<Enterprise>().Property(i => i.Id)
                                         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        modelBuilder.Entity<Company>().HasKey(pk => pk.Id);
        modelBuilder.Entity<Company>().Property(i => i.Id)
                                      .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        modelBuilder.Entity<Company>().HasOptional(t => t.PrimaryContact);

        modelBuilder.Entity<CompanyContact>().HasKey(pk => pk.ContactID);
        modelBuilder.Entity<CompanyContact>().Property(i => i.ContactID)
                                             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    }
}

And here is the Main method where I call the code.

    static void Main(string[] args)
    {
        try
        {
            using (var ctx = new DataContext())
            {
                ctx.Database.Log = Console.Write;

                var ent = ctx.Enterprises.FirstOrDefault(e => e.Id == 1);

                //Exception thrown on this line.
                ctx.Entry(ent).Reference(e => e.Company).Load();

                Console.WriteLine(ent);
                Console.WriteLine(ent.Company);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }

I turned on EF logging and here is the output from running the code (to keep the question shorter, I did not include the full stack trace):

Opened connection at 2/22/2019 3:43:02 PM -06:00
SELECT TOP (1)
    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name],
    [Extent1].[CompanyID] AS [CompanyID]
    FROM [dbo].[Enterprise] AS [Extent1]
    WHERE 1 = [Extent1].[Id]
-- Executing at 2/22/2019 3:43:02 PM -06:00
-- Completed in 85 ms with result: SqlDataReader

Closed connection at 2/22/2019 3:43:02 PM -06:00
Opened connection at 2/22/2019 3:43:02 PM -06:00
SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name],
    [Extent1].[PrimaryContactID] AS [PrimaryContactID],
    [Extent1].[PrimaryContact_ContactID] AS [PrimaryContact_ContactID]
    FROM [dbo].[Company] AS [Extent1]
    WHERE [Extent1].[Id] = @EntityKeyValue1
-- EntityKeyValue1: '1' (Type = Int32, IsNullable = false)
-- Executing at 2/22/2019 3:43:02 PM -06:00
-- Failed in 68 ms with error: Invalid column name 'PrimaryContact_ContactID'.

Closed connection at 2/22/2019 3:43:02 PM -06:00
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'PrimaryContact_ContactID'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrap

And finally, here is the database schema diagram:

Database Diagram

I'm sure that I must be missing something fundamental, but after copious amounts of searching, I have not been able to resolve my problem.

like image 879
Chris Dunaway Avatar asked Oct 16 '22 06:10

Chris Dunaway


1 Answers

You need to enforce [ForeignKey] attribute for navigation properties which don't follow the EF default conventions:

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PrimaryContactId { get; set; }

    [ForeignKey(nameof(PrimaryContactId))]
    public virtual CompanyContact PrimaryContact { get; set; }
}

Otherwise, EF will not recognize your PrimaryContactId property as column for PrimaryContact and it'll create another column instead, PrimaryContact_ContactID.

like image 171
Leonel Sanches da Silva Avatar answered Oct 21 '22 06:10

Leonel Sanches da Silva