【发布时间】:2014-09-03 15:51:19
【问题描述】:
我使用 Code First 来定义现有数据库的架构。我遇到的问题是它们在表中的键名不太一致。这适用于一对多关系,因为我可以使用 HasForeignKey() 方法,但似乎没有对应的一对一关系。我的表定义是:
namespace Data.Mappings {
internal class DocumentTypeConfiguration : EntityTypeConfiguration<Document> {
public DocumentTypeConfiguration() {
ToTable("ProsDocs");
HasKey(m => m.Id);
Property(m => m.Id)
.HasColumnName("ProsDocId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// ---- This is the foreign key ----
Property(m => m.TypeId)
.HasColumnName("ProsDocTypeId")
.HasMaxLength(3);
HasRequired(d => d.DocType)
.WithRequiredDependent(dt => dt.Document);
// I need to specify here that the foreign key is named "DocTypeId" and not "DocType_Id"
}
}
internal class DocTypeTypeConfiguration : EntityTypeConfiguration<DocType> {
public DocTypeTypeConfiguration() {
ToTable("DocType");
HasKey(m => m.Id);
// ---- This is the "child" end of the foreign key ----
Property(m => m.Id)
.HasColumnName("DocTypeId")
.HasMaxLength(4);
Property(m => m.FullName)
.HasColumnName("DocTypeDesc")
.HasMaxLength(255);
Property(m => m.Priority)
.HasColumnName("DocPriority");
// Or would it be easier to define it here?
// HasRequired(m => m.Document)
// .WithRequiredDependent(d => d.DocType);
}
}
}
为了明确模型,每个Document都有一个DocType,外键关系为Document.ProsDocTypeId --> DocType.Id。
有没有办法为一对一关系的键定义列名?
编辑:我猜我的架构不清楚。
dbo.DocType
-----------
DocTypeId char(4) (PK)
DocTypeDesc varchar(255)
dbo.ProsDocs
------------
ProsDocId int (PK)
ProsDocTypeId char(4)
基本上,我需要生成的查询如下所示:
SELECT
[Extent1].[ProsDocId] AS [ProsDocId],
[Extent2].[DocTypeId] AS [DocTypeId]
FROM [dbo].[ProsDocs] AS [Extent1]
LEFT OUTER JOIN [dbo].[DocType] AS [Extent2] ON [Extent1].[ProsDocTypeId] = [Extent2].[DocTypeId]
WHERE [Extent1].[ProsId] = @EntityKeyValue1
但是相反,因为 EF 假设我想使用主键 (dbo.ProsDocs.ProsDocId) 而不是外键 (dbo.ProsDocs.DocTypeId),所以它生成的查询是这样的:
SELECT
[Extent1].[ProsDocId] AS [ProsDocId],
[Extent2].[DocTypeId] AS [DocTypeId]
FROM [dbo].[ProsDocs] AS [Extent1]
LEFT OUTER JOIN [dbo].[DocType] AS [Extent2] ON [Extent1].[ProsDocId] = [Extent2].[ProsDocTypeId]
WHERE [Extent1].[ProsId] = @EntityKeyValue1
区别就在这里:
理想查询:
LEFT OUTER JOIN [dbo].[DocType] AS [Extent2] ON [Extent1].[ProsDocTypeId] = [Extent2].[DocTypeId]
当前查询:
LEFT OUTER JOIN [dbo].[DocType] AS [Extent2] ON [Extent1].[ProsDocId] = [Extent2].[ProsDocTypeId]
我需要在dbo.ProsDocs.ProsDocTypeId 和dbo.DocType.DocTypeId 之间创建一个一对一的关系。 EF 遇到的问题是它只想使用主键而不是外键来创建关系。如何指定外键的列名,以便每个Document 都只有一个DocType?
【问题讨论】:
-
哪个是主体(必须先存在的实体)?
标签: entity-framework ef-code-first entity-framework-6