我使用Code First來定義現有數據庫的模式。我遇到的問題是他們在表中的關鍵名稱不完全對齊。這與一對多關係正常工作,因爲我可以使用HasForeignKey()
方法,但似乎沒有一對一關係的等價物。我的表定義是:EF6 Code First - 使用不匹配的外鍵配置一對一關係
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
的外鍵列名稱?
哪一個是主體(必須先存在的實體)? – 2014-09-03 16:53:54