Reputation: 452
how can i change the value of a field according to another field value in entity framework mirations?
i have a Table named Tbl_Accounts with bellow columns:
In the old version of my program,the 'Code' column has a 3 length digit value,
for example i list some data stored in Tbl_Account in bellow:
Now:I want to change the value of codes like bellow according to the it's parent with migrations:
Note: code value of Record with ID=7:
code value of Record with ID=5:
Upvotes: 0
Views: 639
Reputation: 60493
If you wanna do this in a migration, you can use raw sql.
The Sql (assuming you're working with Sql Server) would look like this (you need a recursive CTE, as an updated value can depend on a "previous" updated value)
WITH cte
AS
(
SELECT id, code
FROM Tbl_Accounts
WHERE parent_id IS NULL
UNION ALL
SELECT u.id, d.code + u.code
FROM Tbl_Accounts AS u
INNER JOIN cte AS d
ON d.id = u.parent_id
)
update t
set t.code = c.code
from cte c
join Tbl_Accounts t on t.id = c.id
If you use Code first migrations, you can put this as a string variable, and just do (in th up method)
Sql(<yourStringVariableContainingTheSql);
You may also execute this query directly in your base(s), by the way.
See sqlFiddle to be sure of the result
Upvotes: 1