我在实体框架中完全是 n00b。已经安装了 Postgresql 和 Npgsql。只是想从一个简单的 DB 测试开始,但我已经遇到了表的 ID 列的问题。
我首先在 postgres(下面的 sql)中手动创建一个简单的表 Score 及其 PK 约束。我使用参数 /retrofitmodel 运行 edmgen2.exe。在列表中,我只检查包含分数表和 edmgen2.exe 然后输出 4 个文件。我将文件复制到 VS2010 项目目录,并将 edmx 包含到项目中。当我打开它的图表时,ScoreID 标有一个 Key 符号。我编写代码来插入一个简单的对象。它第一次执行时有效,但下次我得到:
{“错误:23505:重复键值违反唯一约束\“Score_PK\”“}
我查看数据库,其中一项的 ScoreID 为 0。对我来说,EF 似乎出于某种原因试图创建另一个 ID 为 0 的对象,而不是增加 ID 值。它让我发疯,因为这只是在我开始使用真正的数据库模型之前的一个愚蠢的简单测试。
我努力了:
在图中将 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 文件(已删除 <>):
?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 文件(已删除 <>):
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