linq的表关系解决办法
记得以前解决这些关系的时候,头疼的要命,也没得出个完美的办法。今天看这种“延迟加载”和“立即加载”时,发现问题解决了。
using (DataContext cont = new DataContext()) { cont.Log = Console.Out; DataLoadOptions dl = new DataLoadOptions(); dl.LoadWith<UserInformation>(p => p.SecurityQuestions); dl.LoadWith<UserInformation>(p => p.UsersRoles); cont.LoadOptions = dl; this.dataGrid1.ItemsSource = (from c in cont.UserInformation select c).ToList<UserInformation>(); }
在此代码中使用的DataLoadOptions表示立即加载,而生成的实际代码,就是我们使用的内联接及外联接,上面代码生成的实际指令如下:
SELECT [t0].[id], [t0].[loginname], [t0].[username], [t0].[password], [t0].[email_address], [t0].[locked], [t0].[locked_date], [t0].[last_login_date], [t0].[created_date], [t0].[ip_address], [t0].[security_question], [t0].[security_answer], [t0].[online], [t2].[id] AS [id2], [t2].[user_id], [t2].[role_id], ( SELECT COUNT(*) FROM [dbo].[users_roles] AS [t3] WHERE [t3].[user_id] = [t0].[id] ) AS [value], [t1].[id] AS [id3], [t1].[question] FROM [dbo].[users] AS [t0] INNER JOIN [dbo].[security_questions] AS [t1] ON [t1].[id] = [t0].[security_question] LEFT OUTER JOIN [dbo].[users_roles] AS [t2] ON [t2].[user_id] = [t0].[id] ORDER BY [t0].[id], [t1].[id], [t2].[id]