LINQ to SQL not generating code for association

It’s a good practice to create a proof of concept in a separate project to test out some new features or untested ideas, or to try and fix a certain problem. This way you’re able to focus on the item you want to test without too much other parameters (heaps of code, business logic, …) interfering. Eliminating this extra interference brings you easier and faster to a result.

But sometimes even the smallest lack of focus while setting up the required pieces of your concept can turn your ‘fast search for a solution' into a painful and time consuming hassle. While setting up a simple data layer I ran into the following problem: some parts of my foreign key associations weren’t generated by LINQ. I was not able to access the Product parent property which was connected to my OrderDetail table, while I was able to access the Order parent property without any problem.

LINQ2SQLAssociationMissing

I checked the designer and noticed the association was existing and the properties were set correctly.

LINQ2SQLAssociation

On first sight everything looks fine, but notice the missing ‘key’ symbol on the Product ID field. Even though the association is set correctly, LINQ to SQL isn’t able to create the code for the associated properties without a primary key on the table. Add a primary key (either in the database and refresh or just in the dbml file), resave the dbml and everything is fine again. Happy coding!

Licensed under CC BY-NC-SA 4.0; code samples licensed under MIT.
comments powered by Disqus
Built with Hugo - Based on Theme Stack designed by Jimmy