包括可选的导航属性,其中导航属性Id与实体的主键相同

时间:2013-07-09 18:55:45

标签: c# entity-framework

所以我在创建查询时遇到了问题(好吧,我可以创建查询,但实体框架在尝试加载属性时会中止它。)

我有两个实体:Contact和ExternalContactExtension。

的ContactID

IsInternal

......其他一些数据......

ExternalContactExtension

的ContactID

......其他一些数据......

现在,两个表中的contactId是相同的,但并非所有联系人都是外部联系人(由IsInternal指定)并且具有外部联系人扩展名。

所以问题是当我运行查询并尝试包含外部联系人扩展时。由于ContactId既是主键又是外键,因此它不可为空。我认为EF认为它意味着存在(即使在导航属性上它列在Zero或One)。如果我有任何没有外部联系人扩展名的内部联系人,这会导致我的查询被中止。

这有什么办法吗?或者我是否必须单独获取外部联系人扩展实体?

编辑:我的模特图片:

enter image description here

查询失败(通常更多过滤/包含,但包含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;
    }

错误讯息:

enter image description here

在您尝试使用属性之前,它实际上不会抛出任何消息(然后我会得到一个空引用异常)。

另一个编辑:

我做了一个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确实返回正确的结果/它运行)。因此,实体框架正在进行破坏它的处理。

1 个答案:

答案 0 :(得分:0)

根据聊天情况,解决此问题的最佳方法可能是创建“缺失”ExternalContactExtensionID字段,该字段可以是NULL

只需对数据库稍作调整即可实现。创建一个计算字段并使用以下公式:

CASE WHEN IsExternal THEN ContactID ELSE NULL END

然后EF会看到它的期望,它应该都很好。