Entity framework 使用Postgresql和Npgsql的实体框架
我是实体框架的总n00b。已安装Postgresql和Npgsql。我只是想从一个简单的DB测试开始,但表的ID列已经出现了问题 我首先在postgres(下面的sql)中手动创建一个简单的表分数及其PK约束。我使用参数/model运行edmgen2.exe。在列表中,我只选择包括分数表和edmgen2.exe,然后输出4个文件。我将文件复制到VS2010项目目录,并将edmx包含到项目中。当我打开它的图表时,ScoreID用一个键符号标记。我编写代码来插入一个简单的对象。它在第一次执行时起作用,但下次我得到: {“错误:23505:重复的键值违反了唯一约束\“Score\u PK\”} 我在数据库中查找,其中一项的ScoreID为0。在我看来,出于某种原因,EF试图创建另一个ID为0的对象,而不是增加ID值。这让我抓狂,因为在我开始使用真正的db模型之前,这只是一个愚蠢的简单测试 我试过:Entity framework 使用Postgresql和Npgsql的实体框架,entity-framework,postgresql,npgsql,Entity Framework,Postgresql,Npgsql,我是实体框架的总n00b。已安装Postgresql和Npgsql。我只是想从一个简单的DB测试开始,但表的ID列已经出现了问题 我首先在postgres(下面的sql)中手动创建一个简单的表分数及其PK约束。我使用参数/model运行edmgen2.exe。在列表中,我只选择包括分数表和edmgen2.exe,然后输出4个文件。我将文件复制到VS2010项目目录,并将edmx包含到项目中。当我打开它的图表时,ScoreID用一个键符号标记。我编写代码来插入一个简单的对象。它在第一次执行时起作用
- 将StoreGeneratedPattern属性从None更改为关系图中的Identity,也更改为Computed
- 将这些值也注入到ScoreID属性的ssdl文件中
CREATE TABLE "Score"
(
"ScoreID" integer NOT NULL,
"ScorePoint" integer,
CONSTRAINT "Score_PK" PRIMARY KEY ("ScoreID" )
)
WITH (
OIDS=FALSE
);
ALTER TABLE "Score"
OWNER TO postgres;
保存方法:
using (BoringDBContext dbContext = new BoringDBContext())
{
Score aScore = new Score();
aScore.ScorePoint = 9;
dbContext.AddToScore(aScore);
dbContext.SaveChanges();
}
SSDL文件(已删除):
我找到了我的长问题的简短答案。将数据库中的ScoreID数据类型更改为BIGSERIAL而不是integer,使自动增量工作。手动创建一个序列并将其设置为默认值从来没有,不知道为什么。听起来像是在数据已经存在时重置序列,因此出现重复键错误否,问题是它没有重置,问题是列必须拥有序列才能与EF一起工作。
?xml version="1.0" encoding="utf-8"?
Schema Namespace="BoringDB.store" Alias="Self" Provider="Npgsql" ProviderManifestToken="9.1.2" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="BoringDBstoreContainer">
<EntitySet Name="Score" EntityType="BoringDB.store.Score" store:Type="Tables" Schema="public" /
/EntityContainer>
EntityType Name="Score"
Key
PropertyRef Name="ScoreID"
/Key
Property Name="ScoreID" Type="int4" Nullable="false" StoreGeneratedPattern="Identity"
Propert Name="ScorePoint" Type="int4"
/EntityType
/Schema
edmx:ConceptualModels
Schema Namespace="BoringDB" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"
EntityContainer Name="BoringDBContext"
EntitySet Name="Score" EntityType="BoringDB.Score" /
/EntityContainer
EntityType Name="Score"
Key
PropertyRef Name="ScoreID" /
/Key
Property Name="ScoreID" Type="Int32" Nullable="false" a:StoreGeneratedPattern="Identity" xmlns:a="http://schemas.microsoft.com/ado/2009/02/edm/annotation" /
Property Name="ScorePoint" Type="Int32" Nullable="true" /
/EntityType
/Schema
/edmx:ConceptualModels