解决Ado.NET Entity Framework错误: DefiningQuery and no InsertFunction Error

最近用Ado.NET Entity Framework做项目,采用了POCO的模式来访问与存取数据库。所谓POCO,是Ado.NET Enity Framework (简称Ado.NET EF) 推出的一种新的模式,即Plain Old CLR Object。Ado.NET EF通过对POCO的支持,允许用户定义自己的Entity对象,比通过Ado.NET EF自动生成的对象更为简洁。

在程序的运行中,你也许会发现如下的错误:

Unable to update the EntitySet XXXXXX because it has a DefiningQuery and no element exists in the element to support the current operation.

这错误有点让人摸不着头脑,在Google上搜了半天,终于发现了原因。原来,如果你的数据库中的表,如果没有定义Primary Key,在Ado.NET EF中会被认为这是个View,而不是个Table。如果你用XML编辑器,打开生成的EDMX文件,就会发现,store type不是Table。除此之外,你还会发现如下的警告信息:

”Warning 6002: The table/view ‘TABLENAME’ does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.“

解决方法很简单,去数据库里面,给你的表加上主键,然后更新整个EDMX就可以了。

支持原创技术分享,据说打赏我的人,都找到了女朋友!