且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自动生成实体通过框架的一个Oracle数据库的身份?

更新时间:2023-09-22 22:22:52


StoreGeneratedPattern =身份只是告诉EF该值会。在INSERT生成的DB-一面,它不应该在提供插入语句的值



您还需要在Oracle中创建一个序列:



创建序列ComplaintIdSequence MINVALUE 1 MAXVALUE 9999999从1开始递增1;

和触发器,使表插入使用它:



创建或评论插入之前重新触发CommplaintIdTrigger
的每一行
开始
如果:new.ComplaintId为null,则选择ComplaintIdSequence.nextval到:从new.ComplaintId双;
ENDIF;
端;


I'm using Oracle provider for Entity framework (beta), and I'm facing a problem.

Our tables have Id columns, which are set to be Identity in StoreGeneratedPattern. I thought that EF will automatically do "underlying works", such as create sequences, and get new identity for each record I add to the table. But when I run code to add a new record, such as:

var comment = new Comment
{
    ComplaintId = _currentComplaintId,
    Content = CommentContent.Text,
    CreatedBy = CurrentUser.UserID,
    CreatedDate = DateTime.Now
};

context.Comments.AddObject(comment);
context.SaveChanges();

an Exception still throws, which is

{"ORA-00001: unique constraint (ADMINMGR.CONSTRAINT_COMMENT) violated"}

(CONSTRAINT_COMMENT is the constrain requires that comment identity must be unique.

How do I solve this?

Thank you very much!

StoreGeneratedPattern="Identity" simply tells EF that the value will be generated DB-side on insert, and that it shouldn't supply a value in insert statements.

You still need to create a sequence in Oracle:

create sequence ComplaintIdSequence minvalue 1 maxvalue 9999999 start with 1 increment by 1;

and a trigger to make table inserts use it:

create or replace trigger CommplaintIdTrigger  
before insert on comment for each row 
begin 
  if :new.ComplaintId is null then select ComplaintIdSequence.nextval into :new.ComplaintId from dual; 
  endif; 
end;