在DataGridView中将AutoSizeMode设置为AllCells时出现NullReferenceException

Mar*_*oon 30 c# entity-framework datagridview nullreferenceexception winforms

我手动将实体框架代码第一个表绑定到datagridview.当我将AutoSizeMode设置为AllCells并向表中添加实例时,我在Add期间得到NullReferenceException.

代码运行如下:

dbContext.Persons.Load();
myDataGridView.DataSource = dbContext.Persons.Local.ToBindingList();

myDataGridView.Columns[ "Description" ].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

Person p = new Person();
p.Name = "Tester Alfred";
p.Description = "Description"; //no more properties, only those two (Id Property is annotated as [Key]

dbContext.Persons.Add( p ); // this throws a NullReferenceException
Run Code Online (Sandbox Code Playgroud)

以下是堆栈跟踪的相关部分:

System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
   bei System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
   bei System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassd.<Add>b__c()
   bei System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   bei System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   bei System.Data.Entity.DbSet`1.Add(TEntity entity)
Run Code Online (Sandbox Code Playgroud)

表人员否则是空的.当我删除AutoSize - 指令时一切都很好.

Plattform:使用Studio 2013的.Net 4.5.1中的WInForms; 运行Win8 Pro,EF 6.1.3

编辑:删除了引入第二个gridview的拼写错误

Mar*_*ton 4

AutoSize 所有单元格意味着数据网格视图需要评估每列的结果。EF 需要提供每行的结果。您似乎正在绑定到外键列。如果行中的值与外部表中的行不匹配,则 datagridview 将抛出此错误。EF 有一个问题,即表中的值必须与外表中的值匹配(区分大小写)...无论 SQL 是否区分大小写。EF 正在使用 CLR 执行实体匹配...区分大小写