2017-03-07 53 views
0

我正在使用.NET 4.5.2,EF6和SQL2016。我有一個拉事件信息SQL視圖在EF非空字段上返回null

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 

的vVisitEvent.cs下DataModel.tt是這樣的SQL視圖:

public string CountryName{get;set;} 

有些地方沒有CountryGUID所以國家或地區名稱字段將是空的。我使用了LEFT JOIN,它在SQL studio中正常運行。如果事件位置沒有CountryGUID,它將返回所有帶有CountryName的事件。然而,我在Visual Studio中的下列錯誤,它似乎被空國家或地區名稱造成的:

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) 

任何意見或可能的解決方案?謝謝!

+0

不知道,但它似乎與映射到視圖有關。你是否爲實體的至少一列指定了「[Key]」?如果這是數據庫優先,則關鍵信息不可用(而不是映射到定義PK的表)。 – Alexei

+0

您是使用LINQ to Entities還是執行自定義Sql查詢?如果您使用自定義Sql檢索數據,在我看來,這是映射問題。 – ali

+0

視圖是否返回唯一的行,如果是,哪些字段或字段組合是唯一的? –

回答

0

我想通了。它是數據庫第一,當vVisitEvent被添加到edmx(從數據庫更新)不知何故EF認爲CountryName是一個數據庫密鑰,並把它放在<key>我不得不手動取消選中數據庫密鑰在edmx圖