SQL视图在EF非空字段上返回null

时间:2017-03-07 21:10:54

标签: sql .net entity-framework nullable

我使用的是.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字段为空。我使用LEFT JOIN并在SQL studio中正常运行。如果事件位置没有CountryGUID,则返回CountryName为null的所有事件。但是,我在Visual Studio中遇到以下错误,它似乎是由null 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)

任何想法或可能的解决方案?谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了。它首先是db,当vVisitEvent被添加到edmx(从数据库更新)时,EF认为CountryName是一个数据库密钥并将其放在<key>下我必须手动取消选中“db key&#39;在edmx图中