我对 WPF 和 EF 非常陌生,我正在尝试在数据网格中显示表中的一些数据。我已经从现有数据库中提取了实体模型,并且简单的操作似乎可以工作(获取行数,使用“第一个”)。
我正在使用 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)
内部异常:
我的表有一个多字段主键,其中一些字段可以为空。实体框架不喜欢主键中可以为空的字段。我删除了这些行,效果很好。我已经在寻找不同的解决方案来满足要求,促使我们在某些主键字段中允许空值。
我一直在寻找原因来了解为什么会发生这种情况以及如何解决它,但没有解决方案或建议对我有用。不过,我有一种简单的方法可以从数据库中提取信息。
步骤 1
首先,您需要使用以下代码行提取与数据库关联的 SQL 语句:
String querySQL = db.SALESREP.Sql;
var list = db.Database.SqlQuery<SALESREP>(querySQL).ToList();