Entity Framework - сначала база данных - ошибка недопустимого имени столбца

У меня есть три простых класса, и я подключаю EF6 к существующей базе данных.

Классы следующие

namespace Infrastructure.Models
{

    [Table("Applications")]
    public class Application
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid ApplicationID { get; set; }
        public DateTime DateTime { get; set; }
        public string CompletedZipFileURL { get; set; }
        public virtual BusinessInfo BusinessInfo { get; set; }

        public Application()
        {
            this.ApplicationID = Guid.NewGuid();
            this.DateTime = DateTime.Now;
            this.CompletedZipFileURL = string.Empty;
            this.BusinessInfo = new BusinessInfo();
            this.BusinessInfo.ApplicationID = this.ApplicationID;
        }

    }


    [Table("BusinessInfo")]
    public class BusinessInfo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid BusinessID { get; set; }
        public Guid ApplicationID { get; set; }
        public  string BusinessName { get; set; }
        public  string BusinessType { get; set; }
        public  string StreetAddress { get; set; }
        public  string City { get; set; }
        public  string State { get; set; }
        public  string Zip { get; set; }
        public  string BusinessTelephone { get; set; }
        public  string FEIN { get; set; }
        public  string ILSalesTaxNo { get; set; }
        public  string IncorporateDate { get; set; }
        public virtual ApplicantInfo ApplicantInfo {get;set;}

        public BusinessInfo()
        {
            this.BusinessID = Guid.NewGuid();
            this.ApplicantInfo = new ApplicantInfo();
            this.ApplicantInfo.BusinessID = this.BusinessID;
        }

    }


    public class ApplicantInfo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid ApplicantID { get; set; }

        public  Guid BusinessID { get; set; }
        public  string Name { get; set; }
        public  string Title { get; set; }
        public  string HomeAddress { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public  string EmailAddress { get; set; }
        public  string PhoneNo { get; set; }
        public  string Criminal { get; set; }

        public ApplicantInfo()
        {
            this.ApplicantID = Guid.NewGuid();
        }

    }

}

Мой класс контекста выглядит следующим образом:

    public class SIDEntities : DbContext
    {

        public SIDEntities() : base(Settings.GetSetting("ConnectionString"))
        {
            base.Configuration.ProxyCreationEnabled = false;
            base.Configuration.LazyLoadingEnabled = false;
        }

        public virtual DbSet<Infrastructure.Models.Application> Application { get; set; }
        public virtual DbSet<Infrastructure.Models.BusinessInfo> BusinessInfo { get; set; }
        public virtual DbSet<Infrastructure.Models.ApplicantInfo> ApplicantInfo { get; set; }


    }

В моей существующей базе данных у меня есть следующие имена таблиц и поля:

Приложения (ApplicationID: uniqueidentifier, DateTime: datetime, CompletedZipFileURL: varchar (500))

BusinessInfo (BusinessID: uniqueidentifier, ApplicationID: uniqueidentifier, ...)

ApplicationInfo (ApplicantID: uniqueidentifier, BusinessID: uniqueidentifier, ...)

По какой-то причине, как только я пытаюсь выполнить запрос к корневому приложению POCO, я получаю сообщение об ошибке "{" Неверное имя столбца 'BusinessInfo_BusinessID'. "}".

Я попытался отладить эту проблему, проверяя различные сообщения SO, но примеры / исправления не применимы к моему первому сценарию базы данных.

Запрос, вызывающий исключение:

    public static Infrastructure.Models.Application Find(Guid id)
    {
        using (SIDEntities cntx = new SIDEntities())
        {
            Infrastructure.Models.Application x = new Infrastructure.Models.Application();
            //the line below is where the error occurs
            x = cntx.Application.Where(m => m.ApplicationID == id).SingleOrDefault();
            return x;
        }
    }

Во время отладки я вижу, что запрос, созданный из LINQ, выглядит следующим образом

SELECT     1 AS [C1],     
        [Extent1].[ApplicationID] AS [ApplicationID],     
        [Extent1].[DateTime] AS [DateTime],     
        [Extent1].[CompletedZipFileURL] AS [CompletedZipFileURL],     
        [Extent1].[BusinessInfo_BusinessID] AS [BusinessInfo_BusinessID]    
FROM [dbo].[Applications] AS [Extent1]

Я понимаю, ПОЧЕМУ я получаю сообщение об ошибке, потому что в таблице приложений нет столбца BusinessInfo_BusinessID.

Я был бы очень признателен за любую помощь / указатели, которые я мог бы получить по этому поводу.


person Solo812    schedule 11.12.2015    source источник
comment
Я обновил вопрос, включив в него запрос, вызывающий исключение.   -  person Solo812    schedule 11.12.2015


Ответы (2)


Проверь это

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }

В своем запросе измените Where и SingleOrDefault на:

x = cntx.Application.SingleOrDefault(m => m.ApplicationID == id);

Надеюсь, это поможет

person Daniel Corzo    schedule 11.12.2015
comment
Спасибо, что пытались мне помочь. Я добавил эту аннотацию ко всем трем классам, но все равно получаю ту же ошибку. Я не уверен, что могло быть причиной этого. - person Solo812; 11.12.2015

Я обнаружил, что, поскольку у меня была связь один-к-одному (которая технически не существует на SQL-сервере, мне пришлось добавить аннотацию внешнего ключа под свойством [Key], как указано ниже:

Entity Framework 6: однозначные отношения с наследованием

а также

http://www.entityframeworktutorial.net/entity-relationships.aspx

person Solo812    schedule 11.12.2015