具有可为空列的视图上的唯一索引
本文关键字:视图 唯一 索引 | 更新日期: 2023-09-27 18:31:28
视图 我正确地返回了唯一的结果,但由于视图的设置方式(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 只能为空一次)?
我现在最终使用了这项工作:
如果 Association Id 为 null,则将 AssociationId设置为等于 0,然后从 EmployeeId 和 AssociationId 创建一个主键
ISNULL(dbo.EmployeeJobAssociations.Id, 0) AS AssociationId
在实体框架中:
modelBuilder.Entity<EmployeeJobAssociationView>.HasKey(x => new { x.Id, x.AssociationId});