有人请让我摆脱困境,让我知道自己做过的/没做过的使我的代码失败的事情吗?
我首先使用Entity Framework数据库。当我查询一个实体并请求包含一个相关实体时,出现以下错误:无效的列名“ PrimaryContact_ContactID”。调用Load
方法的行上会抛出异常。
我正在尝试查询Enterprise
实体之一,并使其也包含Company
实体。
(这是复制异常的简化示例)
这是我的实体类:
//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; }
}
这是DataContext
类
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);
}
}
这是Main
方法,我在其中调用代码。
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();
}
我打开了EF日志记录,这是运行代码的输出(为简短起见,我没有包括完整的堆栈跟踪信息):
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
最后,这是数据库架构图:
我确定我必须缺少一些基本知识,但是经过大量搜索之后,我仍无法解决问题。
答案 0 :(得分:3)
您需要对不遵循EF默认约定的导航属性强制使用[ForeignKey]
属性:
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; }
}
否则,EF不会将您的PrimaryContactId
属性识别为PrimaryContact
的列,它将创建另一个列PrimaryContact_ContactID
。
答案 1 :(得分:0)
我遇到了同样的错误,并在我的命名约定中寻找解决方案。我尝试了所有可能的约定和技巧,只是为了找出问题的原因。
我错误地初始化了数据库。我需要一个用于SQLite的初始化程序(示例用法)。这是我的CustomContext中的“ OnModelCreating”方法的工作示例。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var dbi = new SqliteDropCreateDatabaseWhenModelChanges<LogsContext>(modelBuilder);
DB.SetInitializer<LogsContext>(dbi);
base.OnModelCreating(modelBuilder);
}
我希望这样可以在查找错误的过程中为某人节省一些时间。