Search code examples
entity-frameworkoracle11gmany-to-many

EntityFramework with Oracle Insert many to many error


I am using EntityFramework 5.0 to model my Oracle 11g database. I have 3 tables with many to many relationship.

CREATE TABLE za
(id NUMBER(10,0) NOT NULL,
name VARCHAR2(20 BYTE) NOT NULL,
CONSTRAINT za_pk PRIMARY KEY (id));

CREATE TABLE zb
(id NUMBER(10,0) NOT NULL,
name VARCHAR2(20 BYTE) NOT NULL,
CONSTRAINT zb_pk PRIMARY KEY (id)) 

CREATE TABLE zc(
za_id NUMBER(10,0) NOT NULL,
zb_id NUMBER(10,0) NOT NULL,
CONSTRAINT zc_pk PRIMARY KEY (za_id, zb_id),
CONSTRAINT zc_za_fk FOREIGN KEY (za_id) REFERENCES za (id),
CONSTRAINT zc_zb_fk FOREIGN KEY (zb_id) REFERENCES zb (id))

To have auto incremental id when insert record to table, i add sequences and triggers to each table :

CREATE OR REPLACE TRIGGER za_trigger BEFORE INSERT ON za
REFERENCING NEW AS NEW OLD AS OLD FOR EACH ROW
BEGIN select ZA_SEQ.nextval into :NEW.ID from dual;
END; 

CREATE OR REPLACE TRIGGER zb_trigger BEFORE INSERT ON zb 
REFERENCING NEW AS NEW OLD AS OLD FOR EACH ROW
BEGIN select ZB_SEQ.nextval into :NEW.ID from dual;
END;

Now, when i use this code to insert records to database :

ZA za = new ZA();
za.NAME = "ZA1";

ZB zb1 = new ZB();
zb1.NAME = "ZB1";

ZB zb2 = new ZB();
zb2.NAME = "ZB2";

za.ZB.Add(zb1);
za.ZB.Add(zb2);

Entities entities = new Entities();
entities.ZA.Add(za);
entities.SaveChanges();

I receive this error : An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for more details:

  InnerException  : ORA-02291: integrity constraint (SIMCA.ZC_ZB_FK) violated - parent key not found

So how can i insert records to table that has many-to-many relationships?


Solution

  • After a few days I found a solution. When I create model from database, all the ID of entity must have its property StoreGeneratedPattern set to Identity. As shown in this picture