簡體   English   中英

使用Postgresql和Npgsql的實體框架

[英]Entity Framework using Postgresql and Npgsql

我在實體框架上總共n00b。 已經安裝了Postgresql和Npgsql。 只是想從簡單的數據庫測試開始,但是我已經在表的ID列中遇到了問題。

我首先在postgres中手動創建一個簡單的表Score及其PK約束(下面的sql)。 我用參數/ retrofitmodel運行edmgen2.exe。 在列表中,我只檢查包括Score表和edmgen2.exe然后輸出4個文件。 我將文件復制到VS2010項目目錄,並將edmx包含到項目中。 當我打開它的圖表時,ScoreID標有一個Key符號。 我編寫代碼來插入一個簡單的對象。 它在第一次執行時有效,但是下次我得到:

{“錯誤:23505:重復的鍵值違反了唯一約束\\“ Score_PK \\”“}

我查看數據庫,其中一個項目的得分ID為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

我找到了我長期問題的簡短答案。 在數據庫中將ScoreID數據類型更改為BIGSERIAL而不是整數可以使自動增量工作。 手動創建一個序列並將其設置為默認值從來沒有,不知道為什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM