c# - MS Dynamics365 - generate custom serial number, ensure uniqueness
问题描述
I am developing a Dynamics365 CRM based solution, and for a custom entity we've defined, we need to create custom serial numbers.
For various business reasons, neither a GUID nor a sequential numbering scheme will do - business insists on a format of
99-9999-9999
where each group of numbers is basically a random group of numbers.
Creating those in a plugin is easy - but how do I ensure uniqueness?? I'm a C#/SQL Server developer at heart, and in SQL Server / T-SQL, I'd just create an unique index on my "Entity" table on this column. Checking if a newly created number exists would be easy-peasy - just do an
IF EXISTS (SELECT * FROM dbo.MyEntity WHERE SerialNum = @SerialNumGenerated)
check, and since that single column is indexed and NOT NULL
, it would be quite fast, too.
But how do I do the same (at least as "same" as possible) in Dynamics365? How can I programmatically check (inside my C# plugin) if a newly created "serial number" has not yet been used - and do so it's quick enough not to slow down the save process too much? Can I somehow also "index" that property on my custom entity and do something similar to the IF EXISTS()
check in T-SQL ?
Thanks for any hints or pointers!
解决方案
Assuming you are unable to design a generation formula that is astronomically unlikely to generate duplicates (e.g. a GUID). You will need to follow this general logic.
- Run formula to create a unique id.
- Search CRM via
RetrieveMultiple
to check for any records with that number already. - If number already exists; go back to 1.
- Else; update record with new id.
You then have to decide where to execute your code. Two options spring to mind.
In the 'box', e.g. a plugin or JavaScript. In this case you would have the issue that its possible to have multiple executions of your formula concurrently with no knowledge of each other. Depending on how likely your formula is to generate duplicates and the rate that records are created this may be acceptable.
Go out of the 'box', e.g. a console application running on a schedule that finds records without numbers. It then numbers each record one by one. A single threaded approached has the benefit of ensuring uniqueness, but is going to be slower from a user perspective.
If it was me and I had to implement this requirement, I would go for option 2.
推荐阅读
- c# - C# - Selenium 无法从 WebDriver 服务中检索 SessionId
- python - 我的神经网络没有学习成本没有改变
- css - 如何在将前两个单词向左移动时保持正文居中
- python - scipy/numpy 等效于 c++ eigen3 示例
- javascript - jsPDF PubSub 错误 – “字体没有 unicode cmap”
- python - 如何将按钮的尺寸设置为等于 Python tkinter 中的变量?
- oracle - 使用 JSON_TABLE 的子查询给出 ORA-0600 错误
- scala - Scala中的日期字符串不匹配
- clr-profiling-api - 如何使用 ICorProfilerInfo2 从字节数组对象中获取值
- python - 重命名使用编译代码的 Python 模块