所以我在创建查询时遇到了问题(好吧,我可以创建查询,但是实体框架在尝试加载属性时会中止它)。
我有两个实体:Contact 和 ExternalContactExtension。
接触
联系人 ID
是内部的
...一些其他数据...
外部联系人分机
联系人 ID
...一些其他数据...
现在,两个表中的contactId 相同,但并非所有联系人都是外部联系人(由 IsInternal 指定)并具有外部联系人扩展名。
所以问题是当我运行查询并尝试包含外部联系人扩展名时。由于 ContactId 既是主键又是外键,所以它不能为空。我认为 EF 认为这意味着它存在(即使在导航属性上它被列为零或一)。如果我有任何没有外部联系人分机的内部联系人,这将导致我的查询被中止。
有没有办法解决?还是我必须单独抓取外部联系人扩展实体?
编辑:我的模型图片:
失败的查询(通常更多的过滤/包含,但包含 ExternalContactExtension 似乎是唯一可以确定它是否失败的东西):
DataSupplier.GetMany<Contact>(
x => x.Active,
x => x.ExternalContactExtension
).ToList();
GetMany 定义(技术上,由中间类调用,但这只是传递参数):
public virtual IEnumerable<TEntity> GetMany<TEntity>(Expression<Func<TEntity, bool>> where, params Expression<Func<TEntity, object>>[] includeProperties)
where TEntity : class
{
IDbSet<TEntity> set = this.context.Set<TEntity>();
var query = set.IncludeMultiple(includeProperties).AsQueryable<TEntity>();
query = query.Where(where);
this.queryString = "";
this.queryString = query.ToString();
List<TEntity> list = query.ToList();
return list;
}
错误信息:
在您尝试使用属性之前,它实际上不会抛出任何消息(然后我得到一个空引用异常)。
另一个编辑:
我做了一个 SQL 配置文件,EF 正确生成了 SQL:
SELECT
[Extent1].[ContactId] AS [ContactId],
[Extent1].[EmployeeId] AS [EmployeeId],
[Extent1].[IsInternal] AS [IsInternal],
[Extent1].[GroupId] AS [GroupId],
[Extent1].[OldSupplierId] AS [OldSupplierId],
[Extent1].[Active] AS [Active],
[Extent1].[InsertUserId] AS [InsertUserId],
[Extent1].[InsertDate] AS [InsertDate],
[Extent1].[UpdateUserId] AS [UpdateUserId],
[Extent1].[UpdateDate] AS [UpdateDate],
[Extent2].[ContactId] AS [ContactId1],
[Extent2].[Salutation] AS [Salutation],
[Extent2].[FirstName] AS [FirstName],
[Extent2].[MiddleInitial] AS [MiddleInitial],
[Extent2].[LastName] AS [LastName],
[Extent2].[Phone] AS [Phone],
[Extent2].[Fax] AS [Fax],
[Extent2].[Title] AS [Title],
[Extent2].[Department] AS [Department],
[Extent2].[Email] AS [Email],
[Extent2].[Address] AS [Address],
[Extent2].[City] AS [City],
[Extent2].[Territory] AS [Territory],
[Extent2].[Country] AS [Country]
FROM [DataSupplier].[Contact] AS [Extent1]
LEFT OUTER JOIN [DataSupplier].[ExternalContactExtension] AS [Extent2] ON [Extent1].[ContactId] = [Extent2].[ContactId]
WHERE [Extent1].[Active] = 1
(它正确地进行了外连接,并且此 SQL 确实返回了正确的结果/它运行)。所以它是实体框架正在处理破坏它的地方。