开发者

Entity framework code first custom Id

I need to have a custom Id when creating a model. For eg.

These are my constraints:

  1. 8 digits.
  2. based on contraints, an Id must begin with certain number开发者_StackOverflow中文版s.

How do I make sure I generate no duplicates? I'm using a repository pattern, so My save method looks like:

public User SaveUser(User user);


You can be sure that you will not generate duplicates because it is Id = Primary key which must be unique. Once you try to save the entity whit duplicate id you will get an exception.

The generation algorithm depends on many other factors including where do you want to generate Id, how do you want to differ new Id, how complex is the logic for generation and how do constraint changes and one more important thing - can you have a gaps in the sequence of subsequent ids (for example if you rollback transaction with already generated id)? You will have to find your own mechanism based on these requirements.

I did this few times and I used separate table for sequences storing last used number for each sequence type (constraint) + stored procedure for generating next, storing it and returning it back to application + intensive locking / restrictive transaction isolation levels.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜