简体   繁体   中英

EntityFramework Insert into Oracle table with a sequence as PK

I'm doing an insert with EF like this:

        using (Entities1 ctx = new Entities1())
        {
            ADDRESS_RESOLVER addrRes = new ADDRESS_RESOLVER();
            addrRes.ZIP_VEGA = addr.ZipVega;

            ctx.ADDRESS_RESOLVER.Add(addrRes);
            ctx.SaveChanges();
        }

The table ADDRESS_RESOLVER has a primary key ID with a sequence associated. The trigger look like this:

create or replace 
trigger SEQ_ADDRESS_RESOLVER_ID  
   before insert on "MY_DB"."ADDRESS_RESOLVER" 
   for each row 
begin  
   if inserting then 
      if :NEW."ID" is null then 
         select SEQ_ADDRESS_RESOLVER.nextval into :NEW."ID" from dual; 
      end if; 
   end if; 
end;

The problem is my EF object addrRes has the ID settet do 0 and I cannot set it to null because it's a PK so when I try to do the insert the trigger doesn't work. My solution is changing the "if" in the trigger to "0" instead of "null" but I'm not sure if it is the right solution. Is there a smarter way to do this?

As stated by @qujck I needed to change the trigger like this:

    create or replace 
trigger SEQ_ADDRESS_RESOLVER_ID  
   before insert on "MY_DB"."ADDRESS_RESOLVER" 
   for each row 
begin  
   if inserting then 
      if NVL(:NEW."ID", 0) = 0 then 
         select SEQ_ADDRESS_RESOLVER.nextval into :NEW."ID" from dual; 
      end if; 
   end if; 
end;

Another option is to change the property StoreGeneratedPattern of your entities PK to "Identity" (A value is generated on insert and remains unchanged on update.)

With this solution you don't have to touch your database trigger and add the extra if statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM