实体框架NullReferenceException调用ToList?

时间:2010-11-12 19:04:09

标签: entity-framework-4 firebird firebird2.5

我是WPF和EF的新手,我正在尝试从数据网格中的表中显示一些数据。我已经从现有数据库中提取了实体模型,并且简单的操作似乎有效(使用'first'获取行数)。

我使用2.0.5 DDEX提供程序和2.5.2 ADO NETProvider运行Firebird 2.5.0。

当我尝试将数据放入网格或简单地放入列表时,我得到一个空引用异常。

可能我只是不明白如何使用实体框架,但我在网上看到的例子让它看起来很容易。

public partial class Page1 : Page
{
    Entities context;

    public Page1()
    {
        context = new Entities();

        InitializeComponent();

        // This works to get a row into the grid 
        var arep = context.SALESREPs.First();
        var alist = new List<SALESREP>();
        alist.Add( arep );
        gridUserList.ItemsSource = alist;

        // These both fail with null ref exception
        var allreps = context.SALESREPs.ToList();
        gridUserList.ItemsSource = context.SALESREPs;
    }
}

以下是例外情况:

System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=System.Data.Entity
StackTrace:
   at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
   at System.Data.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.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.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)
   at PSUserMaintenanceWebUI.Page1..ctor() in C:\Documents and Settings\d...\my documents\visual studio 2010\Projects\UserMaintenance\UserMaintenanceWebUI\Page1.xaml.cs:line 36
   at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.InvokeDelegate(Action`1 action, Object argument)
   at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CallCtorDelegate(XamlTypeInvoker type)
   at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CreateInstance(XamlTypeInvoker type)
   at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)

InnerException:

1 个答案:

答案 0 :(得分:9)

我的表有一个多字段主键,其中一些字段可以为空。实体框架不喜欢主键中的可空字段。我删除了那些行,它工作正常。我已经在寻找一个不同的解决方案,以促使我们在某些主键字段中允许空值。