我已正确返回视图的唯一结果,但由于视图的设置方式(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
因为我使用EmployeeId作为主要字段(我希望员工不会在我的视图中显示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
是否可以使表具有基于EmployeeId(Id)和AssociationId的索引,即使AssociationId可以为空(但每个EmployeeId只能为空 ONCE )?
答案 0 :(得分:0)
我现在最终使用这项工作:
如果AssociationId为null,则将其设置为等于0,然后从EmployeeId和AssociationId创建主键
ISNULL(dbo.EmployeeJobAssociations.Id, 0) AS AssociationId
并在实体框架中:
modelBuilder.Entity<EmployeeJobAssociationView>.HasKey(x => new { x.Id, x.AssociationId});