Best way to update LINQ to SQL classes after database schema change - c#

I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux.
Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?

You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs.
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe
/server:<SERVER>
/database:<database>
/code:"path\Solution\DataContextProject\dbContext.cs"
/language:csharp
/namespace:<your namespace>

I haven't tried it myself, but Huagati DBML/EDMX Tools is recommended by other people.
Huagati DBML/EDMX Tools is an add-in
for Visual Studio that adds
functionality to the Linq2SQL/DBML
diagram designer in Visual Studio
2008, and to the ADO.NET Entity
Framework designer in Visual Studio
2008 SP1. The add-in adds new menu
options for updating Linq2SQL designer
diagrams with database changes, for
renaming Linq-to-SQL (DBML) and EF
(EDMX) classes and properties to use
.net naming conventions, and for
adding documentation/descriptions to
Linq-to-SQL generated classes from the
database properties.

Here is an easy fix without any additional software, that just works for simple changes (like added fields, few tables, etc).
Instructions:
You pull a copy of the changed table into the designer (will be removed later)
Now select all the new (or changed) fields and (right-click ->) copy
In your original table right click and insert them (delete changed fields first)
Now delete the table you copied them from
I know it is kinda obvious, but somehow non-intuitive, and it helped me a lot, since all the right attributes and types will be copied, and all links stay intact. Hope it helps.
When to use:
Of course it is - as said - for small changes, but surely better than manually replacing tables with many links, or when you don't want your whole database structure generated by SQLMetal. For example when you have a big amount of tables (e.g. SAP), or when using cross-linked tables from different databases.

DamienG has written some t4 templates which can replace some of what VS generates for you. These can be rerun whenever you like via a command line tool.
T4 templates have the added benefit of being editable. This allows you to tweak what is generated to you hearts content.

I think Jeff complained about this recently. One common technique is to drag all the objects into the designer again...
I hope someone else chimes in with a better approach!

I wrote a tool to do script changes to Dbml scripts see http://code.google.com/p/linqtodbmlrunner/ and my blog http://www.adverseconditionals.com

How about modifying the Properties of the entity/table within the DataContext design surface within Visual Studio?
For instance if I added a column to an SQL Server table:
Open the *.dbml file.
Right click the entity and select Add > Property.
Fill out the values in the Properties window for the new column.
Build your solution.
The auto generated model classes should reflect the new column that was added.

Related

Customize T4 template - ADO.Net Entity data model for EF code first from existing database

I am trying to locate and customize the T4 template of ADO.Net Entity data model for EF code first from existing database.
What I want to customize or change is data type mapping. I am using Oracle's ODP.Net provider which supports EF. I am trying to remap the Oracle data type number to Int64 instead of Decimal due to my requirement.
As I am new to editing T4 files for customization I am finding difficulty in locating the template file that does the code first mapping. Any help in pointing me to the right direction is appreciated.
UPDATE Feb 2017: You should check out this amazing EntityFramework Reverse POCO Code First Generator project which consists of T4 templates to do Code First from an Existing Database.
Those templates are very easy to use, fully customizable, and I could easily add my customizations to those templates! Not to mention that they are much more complete than the original EF wizard. The authors/contributors of that project are very friendly and responsive, and I have myself made a few contributions.
_
(Turns out that I was reinventing the square wheel by creating my own T4 templates).
Original Answer (just for reference if helps anyone digging into EF Wizard source code):
I don't know why, but the templates for Model First (EF Designer from database) are easily customizable (but they are EDMX based), while the code for Code First from Database is not that easy - even if you manage to find the templates.
If you right click your project, click "Entity Framework" and "Customize Reverse Engineer Templates" you will get Context.tt, Entity.tt and Mapping.tt inside folder CodeTemplates\ReverseEngineerCodeFirst. However, those templates need to be called by some external caller which should pass some context information to the templates - that's why they are not ready-for-customization as the Model First templates are.
Those are the same templates that you will find in Entity Framework source code (in folder src\PowerTools\CodeTemplates\ReverseEngineerCodeFirst). And in \src\PowerTools\Handlers\ReverseEngineerCodeFirstHandler.cs you will find the method ReverseEngineerCodeFirst that reads the metadata from the database and passes to those templates. That caller method can be copied into its own T4 template (so you don't need to build that Power Tools and install in your Visual Studio), but it has some interaction with Visual Studio and with the Project, which would be hard to do with plain T4 templates.
I created a T4 template based on that method mentioned above, basically by putting together all classes/helpers that the ReverseEngineerCodeFirstHandler.cs needs, and removing references to the Visual Studio DTE. There are some instructions on my template, but basically you should remove the include for EF.Utility.CS.ttinclude, and comment out the variables "var efHost" and "var code"
Those templates that you will find in folder CodeTemplates\ReverseEngineerCodeFirst are almost identical to the Code First From Database wizard, except for some minor differences:
The wizard creates one-to-many navigation properties as HashSet<T>, while the templates creates those as List<T>
The wizard uses nullables like int? while the other uses Nullable<int>
The wizard adds some code-analysis suppression attributes [SuppressMessage]
The wizard creates the DbSets as virtual, while the templates don't.
The wizard generates part of the mappings using Data Annotations (like [Table], [Key], [StringLength], etc) and the other parts (properties and relationships) inside DbContext.OnModelCreating. The T4 templates generate all mappings inside configuration classes for each entity (EntityTypeConfiguration<Entity>).
Most of those differences can be easily adjusted, although I don't think it really matters. If you want to make strong customizations (like I did on my templates, which include automatic infer of non-existing relationships, relationships to views, class inheritance), I suggest that you create your own DTOs (or POCOs) for passing Entities/Properties/NavigationProperties to the included templates. In my case I use the original EdmMapping, map it into my DTOs, make a lot of modifications on those DTOs (based on my company standards), and pass those DTOs to the T4 includes (with small modifications).

"Update Model from Database" wizard is deleting mappings of renamed POCO classes

I'm building an application using EF 5 to talk to an existing Oracle database. I'm not allowed to change any part of the DB schema. I have generated my model from the database using the VS2012 wizard, and all classes are named after their Oracle counterparts.
The naming of objects in the database is QUITE_UGLY_AND_INCONSISTENT, so I'd like to rename the POCO classes and properties. I can easily do that from the EDM Designer. As a result, I get neatly named class and property names, that are mapped to the UGLY_NAMED tables from the DB. I can successfully perform queries and everything works smoothly. Exactly what I wanted.
However, when I need to add new tables to the model, I run the "Update Model from Database" wizard and check the additional tables to import. It suddenly lists my renamed (but still correctly mapped) classes under the Delete tab, saying it can't find them in the database. When I click Finish, my existing classes are unmapped and I have to manually re-map each property to its corresponding DB column... Or roll back to the previous version of the EDMX file from version control.
I'm looking for what you think would be the most elegant solution to this problem, since I need the application to be as maintainable as possible. I strongly favour an approach that lets me auto-generate new classes from the database while preserving the existing renamed objects and their mappings.
Am I overlooking some way to prevent the Update Model wizard from deleting my existing mappings?
Should I use a different approach to renaming the generated classes?
Should I leave the generated classes unchanged and instead construct sanely-named wrapper classes that are exposed to the rest of my application?
Should I refrain from auto-generation and instead go for a code-first approach? This is a very unfavorable option, because I need the time spent on manual model coding and mapping to be as little as possible. Adding objects will be a very frequent task.
Should I perhaps even use a different ORM altogether..?
I discovered the culprit myself: running the "Generate Database from Model" wizard due to a recommendation in an article I read somewhere. It changed all the model's underlying table and column names to SQL Server standard names ([dbo].[Customers].[CustomerID] etc.).

Adding a new table to EF

We are upgrading an old VB6 application which sits on a SQL Server 2005 database, to an Entity Framework solution. The database remains the same, except - we're adding a new table. Is it possible with Entity Framework, to maintain the existing structure, when it gets installed on a client PC - and just add one new table?
Is this how Code First will work? Can I be 100% certain that no other tables will be modified?
i don't think, the effort is worth it to switch to code-first if you have an existing database and want to add only one table.
it is possible to map code-first classes to an existing database (reverse engineer code first). actually, i'm not very experienced with that workflow, but i know you can. You have to deal with a lot of manual mapping (with DataAnnotations or Fluent API), so in your case i would recommend to use the Entity Framework Database First workflow, since adding a single table saves you a lot of work.
this link has some useful information: Arthur Vickers Blog - Don't use Code first by mistake
You have two options, use a database editor such as SQL management studio to create the table which you can then map to a ef entity, or use migrations for ef which will let you update your database via ef.
Take a look at the migrations tutorial here: http://msdn.microsoft.com/en-gb/data/jj591621
I am using the database first approach, since a database developing team is doing the changes I require in the database on the SQL server for me.
Hence, I have to update the EDMX whenever the schema in the database changes.
Note: Changing one single table directly does not work for me, because VS doesn't always detect the changes right (for this issue, here are some details in SO if you're interested).
Hence, I am using the following workaround (regenerating all the tables):
In VS 2012, open the EDMX file by double-clicking on it. The graphic representation of the tables is shown.
Left-Click into the EDMX designer, then select all tables by pressing CTRL+A. Then, remove them by pressing DEL.
Right-Click into the EDMX designer and select "Update Model from Database ..." in the context menu.
The Update Wizard opens. In the "Add" tab, check "Tables", and depending on the requirements, check "Pluralize or singularize generated object names", "Include foreign key columns in the model" and optionally "Import selected stored procedures and functions into the entity model". Usually, I am using the "Pluralize..." and "Include foreign key columns..." options.
Click Finish. Now Save by pressing Ctrl+S.
That workaround works fine for me, and requires just a minute to update the model reliably.

How to use LINQ for CRUD with a simple SQL table?

Every LINQ blog I found there seemed around 2 years old, I understand the syntax but need more direction on creating the SQL mapping and context classes.
I just need to use LINQ for 2 SQL tables I have, nothing complicated. Do folks write the SQL mapping classes by hand for such cases or is there a decent tool for this?
Can someone point me in the right direction?
In your project right-click to open the context menu
Add new item
Linq-to-Sql data classes
Open the created dbml file in the design view
Open the servers view
Connect to your database
Drag-and-drop your tables to the design view of the dbml
and you are ready to go!
If you want to avoid using or generating a dbml file (with the editor or not), I believe you can use SqlMetal to generate a set of code files from a database.
More info here: http://msdn.microsoft.com/en-us/library/bb386987.aspx
Example:
Generate source code from SQL metadata directly:
sqlmetal /server:myserver /database:northwind /namespace:nwind /code:nwind.cs /language:csharp
You just add a "Linq to Sql data classes" project item to your project. Then you open server explorer, choose your database and drag the tables in question on to the design surface and you are done.
If you are using a compact sql database look at SqlMetal Builder. This is a gui driven program to generate the dbml file. This is then added to the project. I have found this tool to give me the best results.

Need to generate EDMX files and compile them

My question might be little bit different or basic for advanced users here.
I have a web application which is customizable by administrators. This means, the admin can add new table schema or edit table columns, add new table columns etc. These changes are mapped to our logical objects (much similar to EDMX) which is published after the change. While publishing we generate Stored procedures with necessary changes that are required.
From UI we use these Logical objects to connect DB (using COM which understands the mapping and executes appropriate sprocs and views etc). Now i am thinking to use EF for replacing the Logical objects model which we are having currently. I can create the EDMX files (csdl,msl, ssdl, cs files) dynamically but i am not sure how to compile them and package the classes into DLL dynamically. This means, when i click the button the all edmx related files will be created and DLLs must be created based on CS files and the website must be able to access the new changes in the code.
Can you help me how to automatically and dynamically compile the cs files. I will not have the source code of other files (like default.aspx and others) at customer's end.
Thanks
Albert
Bepenfriends - rather than attempting a CSC from a shell, consider using a CSharpCodeProvider.CompileAssemblyFromFile.
One thing to be careful of: if you compile code and then try to compile it again, you may lock up on the assembly that was created. For this I created an AsyncCompiler which creates a new AppDomain, compiles in there, and then unloads the AppDomain.
It's some pretty hairy code but I'm doing this (generating the AEF XML files, generating code from them, and then compiling everything into an assembly) and it works well. The only thing I don't have quite right is dynamically importing stored procedures - my SSDL has them but not the CSDL or MSL. The search for a solution led me here.
I hope the keywords here are enough to set you off in the right direction.
I don't really have a definitive answer for you just yet - but two potential solutions you could look into, possibly in the near future:
1) There's a set of CodeSmith templates called PLINQO which generate your Linq-to-SQL model (DBMX) and its associated *.cs files from your database. I asked them about Entity Framework support myself, and they confirmed to be working on it - so maybe they'll have that some time soon.
Since those are code and model generation templates, you could definitely take those for Linq-to-SQL and tweak them for EDMX, too. A bit of work, but definitely possible. Once you have the *.cs files and the *.edmx model, you can generate a resulting assembly from it using the CSC (C#) command-line compiler that's installed on every machine which has .NET installed.
2) With .NET 4, the new Entity Framework 4 will include T4 templates (another code generation technology) which will allow you to customize your code generation. Same story applies here - you could externally generate your EDMX model and associated *.cs files for the classes and generate an assembly on the fly from those templates.
See another blog post on that topic, and you should find lots of information when gooling (or binging) or "EF4 T4 templates".
Hope that helps at least a little bit!

Categories