SQL 在 EF 非空字段上查看 returns 空

SQL View returns null on a EF not null field

我正在使用 .NET 4.5.2、EF6 和 SQL2016。我有一个提取事件信息的 sql 视图

CREATE VIEW [dbo].[vVisitEvent]
AS
SELECT
ev.[GUID] as EventID,
vt.[GUID] as VisitorID,
cr.Name as CountryName
FROM [Event] ev
  INNER JOIN (
  [Location] lc 
  LEFT JOIN [Country] cr ON lc.CountryGUID = cr.GUID
) ON ev.LocationGUID = lc.GUID

DataModel.tt下的vVisitEvent.cs是这样的:

public string CountryName{get;set;}

有些位置没有 CountryGUID,因此 CountryName 字段将为空。我在 SQL 工作室中使用了 LEFT JOIN 并且 运行 正确。如果事件位置没有 CountryGUID,它会返回所有 CountryName 为 null 的事件。但是,我在 Visual Studio 中收到以下错误,这似乎是由空 CountryName:

引起的
   System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.Entity.Core.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
   at System.Data.Entity.Core.EntityKey.GetHashCode()
   at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at System.Data.Entity.Core.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
   at System.Data.Entity.Core.Objects.ObjectStateManager.FindEntityEntry(EntityKey key)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

有什么想法或可能的解决方案吗?谢谢!

我想通了。首先是数据库,当 vVisitEvent 添加到 edmx(从数据库更新)时,EF 认为 CountryName 是数据库键并将其放在 <key> 下,我不得不在 edmx 图中手动取消选中 'db key'