I am creating LINQ-to-SQL DataContext and entity classes for a database. The database has several tables, two of which are [AccountMaster] and [AccountCodes]. There is a foreign key relationship between them, and [AccountMaster] .AccountNumber refers to [AccountCodes].
Adding the LINQ-to-SQL file to VS2008 and dragging these tables into the DBML design project creates the collection of accounts in the AccountMaster class accordingly. Meanwhile, using SQLMetal to generate a DataContext does not create EntitySet collections.
Designer Output:
[Table(Name="dbo.A01_AccountMaster")] public partial class A01_AccountMaster
SQLMetal output:
[Table(Name="dbo.A01_AccountMaster")] [DataContract()] public partial class A01_AccountMaster
I follow the guidance in
http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
I tried to generate the DBML file first with SQLMetal, and then generate the DataContext.cs file from the resulting DBML:
sqlmetal.exe /server:srv /database:db /user:usr /password:pwd /sprocs /namespace:AccountContext /context:AccountContext /dbml:AccountContext.dbml /language:csharp /serialization:unidirectional sqlmetal.exe /sprocs /namespace:AccountContext /context:AccountContext /code:AccountContext.cs /language:csharp /serialization:unidirectional AccountContext.dbml
This does not create an association. In fact, checking DBML files from SQLMetal compared to the designer view:
Design View DBML:
<Type Name="A01_AccountMaster"> <Column Name="AccountNumber" Type="System.Int64" DbType="BigInt NOT NULL" CanBeNull="false" /> <Association Name="A01_AccountMaster_A01aAccountNote" Member="A01aAccountNotes" ThisKey="AccountNumber" OtherKey="AccountNumber" Type="A01aAccountNote" /> </Type>
SQLMetal DBML:
<Type Name="A01_AccountMaster"> <Column Name="AccountNumber" Type="System.Int64" DbType="BigInt NOT NULL" CanBeNull="false" /> </Type>
Thus, the association is already absent at the DBML stage.
Since the database contains many tables / sprocs, it is not practical to use a constructor to regenerate the DataContext classes. How to force SQLMetal to create associations correctly?
EDIT:
Running SQLMetal in the entire database, I realized that SOOME entity associations are generated correctly. The foreign key in AccountNotes is defined as:
ALTER TABLE [dbo].[A01aAccountNotes] WITH CHECK ADD CONSTRAINT [FK_A01aAccountNotes_A01_AccountMaster] FOREIGN KEY([AccountNumber]) REFERENCES [dbo].[A01_AccountMaster] ([AccountNumber]) GO ALTER TABLE [dbo].[A01aAccountNotes] CHECK CONSTRAINT [FK_A01aAccountNotes_A01_AccountMaster] GO
EDIT2:
I noticed that correctly created associations are those that have the DEL DELETE CASCADE / UPDATE rule. Is it pointless to create associations that do not have this rule, strictly defined at the database level?