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: уникальный идентификатор, DateTime: дата и время, CompletedZipFileURL: varchar (500))
BusinessInfo (BusinessID: уникальный идентификатор, ApplicationID: уникальный идентификатор,...)
ApplicationInfo (ApplicantID: уникальный идентификатор, BusinessID: уникальный идентификатор,...)
По какой-то причине, как только я пытаюсь выполнить запрос к 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".
Я был бы очень признателен за любую помощь / указатели, которые я мог получить на этом.
2 ответа
Проверь это
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BusinessID { get; set; }
В вашем запросе измените Where и SingleOrDefault на:
x = cntx.Application.SingleOrDefault(m => m.ApplicationID == id);
Надеюсь, поможет
Я обнаружил, что, поскольку у меня было отношение "один к одному" (которое технически не существует на сервере SQL, мне пришлось добавить аннотацию внешнего ключа под свойством [Key], как отмечалось:
Entity Framework 6: отношения один к одному с наследованием
а также
http://www.entityframeworktutorial.net/entity-relationships.aspx