AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 05.05.2011, 00:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
axdaily: Unit of Work
Источник: http://axdaily.blogspot.com/2011/05/unit-of-work.html
==============

After the post about surrogate keys I was asked the following question:
There is the following problem with using surrogate keys.
A record gets RecId value at the moment it is inserted into the database. What if we are doing bulk insert of a journal with many lines and the journal header contains some totals calculated based on its lines. It is impossible to insert lines before header since the value of the journal's surrogate key is unknown. But that would be so convenient because otherwise the header should be inserted first, then the lines and then the header should be updated with the calculated totals.


The answer is – use Unit of Work. It allows to perform create, update and delete operations without worrying about the order of those and without a need to specify surrogate key values. It will all be done automatically in the kernel!

Example:
Let we have the following tables:


The following job will insert the journal header with calculated totals and 10 lines. Note, that there is no place where surrogate keys are mentioned in the code. Business data only.


And here is the result.



Some more details about the unit of work feature:
  1. All database operations happen only when saveChanges() method is invoked.
  2. UnitOfWork class has insertOnSaveChanges(), updateOnSaveChanges() and deleteOnSaveChanges() methods for CUD operations.
  3. Surrogate keys can be propagated automatically to related records if buffers are linked via navigation methods (AJournalLine.header() method in the example). Navigation methods can be created automatically from relations. I’ll write a separate post about them.
And the last but not least. AX client has the great support of the unit of work as well. This means that form datasources can be grouped into a unit of work, so all the benefits of simultaneous commit and surrogate key propagation will be available on forms. There are a lot of possibilities and tricks there, so this topic worth one or more dedicated posts as well.


Источник: http://axdaily.blogspot.com/2011/05/unit-of-work.html
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
Старый 05.05.2011, 06:45   #2  
mazzy is offline
mazzy
Участник
Аватар для mazzy
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
29,472 / 4494 (208) ++++++++++
Регистрация: 29.11.2001
Адрес: Москва
Записей в блоге: 10
1. автор, появись, пожалуйста, дай тебе спасибов накидать.
2. э-э-э... колдунство какое-то. а откуда появился метод line.header()? Он где-то объявлен или в ядре сидит? если объявлен, то как? если в ядре, то он один такой? как я могу привязать line к нескольким структурам?
__________________
полезное на axForum, github, vk, coub.
Старый 05.05.2011, 08:00   #3  
TasmanianDevil is offline
TasmanianDevil
Мрачный тип
Аватар для TasmanianDevil
Злыдни
 
885 / 389 (14) ++++++
Регистрация: 24.01.2005
Адрес: Томск
Отличная штука !!!
Только вот сразу вопрос - данный класс способен только с парой таблиц или с большим числом работать ?
__________________
Мы летаем, кружимся, нагоняем ужасы ...
Старый 05.05.2011, 08:13   #4  
S.Kuskov is offline
S.Kuskov
Участник
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
 
3,429 / 1772 (66) ++++++++
Регистрация: 28.04.2007
Адрес: Калуга
Цитата:
Сообщение от mazzy Посмотреть сообщение
2. э-э-э... колдунство какое-то. а откуда появился метод line.header()? Он где-то объявлен или в ядре сидит? если объявлен, то как?
Цитата:
Сообщение от Blog bot Посмотреть сообщение
Surrogate keys can be propagated automatically to related records if buffers are linked via navigation methods (AJournalLine.header() method in the example). Navigation methods can be created automatically from relations. I’ll write a separate post about them.
и судя по вот этому скриншоту Programmability Concepts
на relation появились свойства CreateNavigationPropertyMethods и NavigationPropertyMethodNameOvverride, которые видимо как раз и отвечают за создание навигационных методов

Интересно всё это. Получается, что при таком подходе, процесс внесения изменения в БД скрыт от программиста и уже нельзя полагаться на то что требуемые операции будут выполнены в нужной последовательности. Нет оно и понятно, для этого UnitOfWork и предназначен. Просто непривычно мыслить не процедурно а декларативно.

Последний раз редактировалось S.Kuskov; 05.05.2011 в 08:23.
Старый 05.05.2011, 11:54   #5  
gigz is offline
gigz
Участник
MCBMSS
Соотечественники
 
19 / 43 (2) +++
Регистрация: 15.09.2008
Цитата:
Сообщение от S.Kuskov Посмотреть сообщение
и судя по вот этому скриншоту Programmability Concepts
на relation появились свойства CreateNavigationPropertyMethods и NavigationPropertyMethodNameOvverride, которые видимо как раз и отвечают за создание навигационных методов
да, именно так.
с этими методами тоже много всего интересного. например, если их использовать на формах, то если соостветствующая запись была выбрана каким-нибудь датасорсом, то она будет использована. иначе будет запрос на чтение. довольно удобно.

Цитата:
как я могу привязать line к нескольким структурам?
такой метод можно объявить для каждого отношения.
__________________
Blog: http://axdaily.blogspot.com

Последний раз редактировалось gigz; 05.05.2011 в 11:57.
За это сообщение автора поблагодарили: mazzy (5), Владимир Максимов (5).
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
mfp: AX6 sneak preview - X++ Unit test improvements Blog bot DAX Blogs 4 05.06.2009 10:56
Механизм отслеживания событий в Work Flow sergeyjb Dynamics CRM: Разработка 5 07.10.2008 11:47
mfp: Late night discussions on software development #3: Unit testing Blog bot DAX Blogs 6 17.03.2008 12:01
axaptapedia: Unit Testing Blog bot DAX Blogs 0 19.11.2007 03:24
Dynamics AX: Dynamics AX 4.0 - Unit Testing and Test Projects Blog bot DAX Blogs 0 28.10.2006 16:40

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 07:02.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.