2014-11-20 115 views
0

視圖我已正確地返回唯一的結果,但由於視圖的設置方式(Id字段是從我的EmployeeId表)實體框架試圖緩存結果,並不讀取場(從而錯誤,因爲它認爲它發現重複鍵)唯一索引的視圖與空列

我有以下的表(此處簡化):

Employee 
    Id 
    Name 

Jobs 
    Id 
    Name 

EmployeeJobAssociations 
    Id 
    EmployeeId 
    JobId 
    StartDate 
    EndDate 

EmployeeJobsView 
    Id (This is actually EmployeeId) 
    AssociationId (This is EmployeeJobs's Id) 
    JobId (Job's table Id) 
    Name (EmployeeName) 
    JobName 
    StartDate 
    EndDate 

視圖代碼如下:

SELECT  dbo.Employees.Id, dbo.EmployeeJobAssociations.Id AS AssociationId, 
       dbo.Jobs.Id as JobId, dbo.Employees.Name, dbo.EmployeeJobAssociations.StartDate, 
       dbo.EmployeeJobAssociations.EndDate, Job.Name AS JobName 
FROM   dbo.Jobs AS Job INNER JOIN 
       dbo.EmployeeJobAssociations ON Job.Id = dbo.EmployeeJobAssociations.JobId RIGHT OUTER JOIN 
       dbo.Employees ON dbo.EmployeeJobAssociations.EmployeeId = dbo.Employees.Id 

,是因爲我使用的僱員作爲主要領域(我想員工沒有JobAssociation誰在我的視圖顯示爲好)實體框架認爲,對某個員工的所有結果都是一樣的:

Id  AssociationId  JobId ...  StartDate 
1234  1      1    10/10/10 
1234  2      2    11/11/10 // Unless I turn off tracking it thinks this is the same as the first row 
2222  null    null    null 

儘管AssociationId可以爲空(但每個EmployeeId只能爲空)(ONCE),是否可以使表具有基於EmployeeId(Id)和AssociationId的索引?

回答

0

我結束了各地使用這項工作現在:

設置AssociationId等於0,如果它空,然後創建關閉僱員和AssociationId

ISNULL(dbo.EmployeeJobAssociations.Id, 0) AS AssociationId 

,並在實體框架的主鍵:

modelBuilder.Entity<EmployeeJobAssociationView>.HasKey(x => new { x.Id, x.AssociationId});