2012-10-22 78 views
3

因此,讓我們假設我有以下實體及其上下文配置設置如下。我省略了很多的屬性爲簡潔起見:一個實體是否可以被多個實體關聯?

public class Company { 
    public int Id { get; set; } 
    public Location Location { get; set; } 
} 

public class Customer { 
    public int Id { get; set; } 
    public Location Location { get; set; } 
} 

public class Location { 
    public int Id { get; set; } 
} 

public sealed class EntityDefaultContext : DbContext { 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) { 
     modelBuilder.Entity<Company>().HasKey(m => m.Id).ToTable("Company"); 
     modelBuilder.Entity<Company>().Property(m => m.Id).HasColumnName("Id"); 
     modelBuilder.Entity<Company>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId")); 

     modelBuilder.Entity<Customer>().HasKey(m => m.Id).ToTable("Customer"); 
     modelBuilder.Entity<Customer>().Property(m => m.Id).HasColumnName("Id"); 
     modelBuilder.Entity<Customer>().HasRequired(m => m.Location).WithRequiredDependent().Map(m => m.MapKey("LocationId")); 

     modelBuilder.Entity<Location>().HasKey(m => m.Id).ToTable("Location"); 
     modelBuilder.Entity<Location>().Property(m => m.Id).HasColumnName("Id"); 
    } 
} 

因此,大家可以看到,無論是公司和客戶的實體持有的位置實體的引用。我相信通常會有的東西。

設置我的DB上下文只是因爲你還可以看到。但是,EF生成的SQL是非常低效的:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[LocationId] AS [LocationId], 
    [Extent3].[Id] AS [Id1] 
FROM 
    [dbo].[Customer] AS [Extent1] 
LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[LocationId] 
LEFT OUTER JOIN [dbo].[Company] AS [Extent3] ON [Extent1].[LocationId] = [Extent3].[LocationId] 
LEFT OUTER JOIN [dbo].[Company] AS [Extent4] ON [Extent1].[LocationId] = [Extent4].[LocationId] 

,當我做這樣的事情這是產生:

var q = from c in defaultContext.Set<Customer>().Include(m => m.Location) 
     select c; 

我做它像這樣的不相關的問題的原因。奇怪的是,這裏是SQL如果我只配置位置實體僅由客戶實體相關聯:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[LocationId] AS [LocationId] 
FROM 
    [dbo].[Customer] AS [Extent1] 
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[LocationId] = [Extent2].[Id] 

這是我期望的那樣。這讓我想。 EF不支持這種情況嗎?它怎麼會沒有?

在此先感謝。

+0

這不可能是正確的。當您查詢客戶時,爲什麼它會加入公司?沒有向後導航屬性返回給公司。在派系中,儘管事實上你已經包括了位置,但位置甚至不是查詢的一部分。所以,無論你是在提出錯誤的問題,還是在發生一些非常奇怪的事情。請注意查詢如何在選擇字段中列出Extent3,但未在From中定義Extent3? –

+0

爲什麼你將它映射爲一對一?嘗試將其映射爲一對多,其中位置可以有多個客戶和公司。 –

+0

@MystereMan你說得對。這是我的錯誤。我爲第二個示例發佈了不正確的代碼片段。我現在修好了。 – 9ee1

回答

3

你原來的映射使用一個一對一的關係。這總是會導致一些特殊的行爲。而且它還有其他一些要求能正確工作。你可能需要的是一個一對多CustomerLocationCompanyLocation之間的關係。更改WithRequiredDependentWithMany,它應該工作。

+1

謝謝。是否有「特殊行爲」存在於任何地方?我查看了MSDN上的RequiredNavigationPropertyConfiguration.WithRequiredDependent,並沒有讀到任何有關此行爲的信息。 –

相關問題