My workflow has been to develop models incrementally using EF designer and generating the database from that model as I progress.
Recently I wanted a computed column so I made a string property, set StoreGeneratedPattern=Computed, and manually changed the generated DDL to be a computed column. This passes its test.
However, if I regenerate the database from the model later, I would have to re-manually change the computed column, and that isn’t really worth the effort.
After browsing Google a bit, I couldn’t find a solution, but managed to come up with using a DDL trigger.
I am curious if there is another, non DDL trigger method of acomplishing the same thing.
Update: I decided to go with the DDL trigger solution below, though I’m still interested if this is unnecessary, but I suspect my problem comes from being in the minority with my workflow style and most others don’t have this issue because they generate the model from the database…
--
-- DDL Trigger for CREATE TABLE
--
alter trigger ddltrigCreateTable
on database
for create_table
as
--
-- Table DirectTrackInfoes
--
if EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')='DirectTrackInfoes'
begin
--
-- Computed Column BaseUrl
--
alter table DirectTrackInfoes
drop column BaseUrl
alter table DirectTrackInfoes
add BaseUrl as ((N'https://'+[ClientDomain])+N'/apifleet/rest')
--
-- Initial data
--
insert into [DirectTrackInfoes] ([Version], [ClientDomain], [ClientId], [AccessId], [UserName], [Password])
values (N'1_0', N'foo.com', 9999, 1, N'', N'')
end
--
-- Table HttpMethods
--
if EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')='HttpMethods'
begin
--
-- Initial data
--
insert into HttpMethods (MethodName)
values (N'GET'), (N'POST'), (N'PUT'), (N'DELETE')
end
go
Using DDL trigger to handle this situation is really not a good idea. If you want to avoid deletion of your existing changes to the database build your database in real incremental way (without deleting current state). This is possible for example with Database Generation Power Pack (you must have at least VS 2010 Premium with database features). There are other supporting tools allowing incremental DB development like Huagati EDMX tools or LLBGen Designer but those tools are usually commercial.
Another more complex option is adding your database customization directly to your EDMX. If anybody comes to your application he should be able to generate database from model and use it without any further steps. Achieving this is little bit complex but it is possible. Check this answer about changing data type in database – same approach can be used for adding any other customization into your database generation workflow.