LINQ to SQL Eager加载1到多个和多对多关系

时间:2011-05-04 09:05:14

标签: linq-to-sql eager-loading

我是使用Linq to SQL的新手,我有一个问题

这是我模特的一部分:

  • 访问>访问产品<产品
  • 访问> VisitSample<产品
  • 访问> VisitStatus

我想急切加载所有相关实体的访问实体,但它给了我一个“InvalidCastexception”。 ,我使用这段代码:

using (TeamsExcellenceDataContext context = new TeamsExcellenceDataContext())


{


            DataLoadOptions lo = new DataLoadOptions();
            context.DeferredLoadingEnabled = false;
            lo.LoadWith<Visit>(v => v.Visitstatus);
            lo.LoadWith<Visit>(v => v.VisitProducts);
            lo.LoadWith<Visit>(v => v.VisitSamples);

            context.LoadOptions = lo;
            var temp = (from v in context.Visits
                   where v.VisitID == visitID
                   select v).Single();
            Visit v = temp;
        }

生成的SQL语句分为两部分(我不知道为什么会这样?):

SELECT [t0].[VisitID], [t0].[StartDate], [t0].[EndDate], [t0].[TypeID], [t0].[StatusID], [t0].[NextObjective], [t0].[CpFeedback], [t0].[Feedback], [t0].[AccID], [t0].[CustMPID], [t0].[AccTreeID], [t0].[RepPermitDays], [t0].[ModeTypeID], [t0].[Recurrence], [t0].[RecurrenceParentKey], [t0].[CDate], [t2].[VisitID] AS [VisitID2], [t2].[ProductID], [t2].[VisitProductTurn], [t2].[CDate] AS [CDate2], (
    SELECT COUNT(*)
    FROM [dbo].[VisitProducts] AS [t3]
    WHERE [t3].[VisitID] = [t0].[VisitID]
    ) AS [value], [t1].[VisitStatusID], [t1].[VisitStatusName], [t1].[VisitStatusMarker], [t1].[CDate] AS [CDate3]
FROM [dbo].[Visits] AS [t0]
INNER JOIN [dbo].[Visitstatus] AS [t1] ON [t1].[VisitStatusID] = [t0].[StatusID]
LEFT OUTER JOIN [dbo].[VisitProducts] AS [t2] ON [t2].[VisitID] = [t0].[VisitID]
WHERE [t0].[VisitID] = @p0
ORDER BY [t0].[VisitID], [t1].[VisitStatusID], [t2].[ProductID]
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [411]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

SELECT [t0].[VisiteID], [t0].[ProductID], [t0].[SampleQuantity], [t0].[CDate]
FROM [dbo].[VisitSamples] AS [t0]
WHERE [t0].[VisiteID] = @x1
-- @x1: Input Int (Size = -1; Prec = 0; Scale = 0) [411]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1/

如果省略此行,则不会发生异常:

lo.LoadWith<Visit>(v => v.Visitstatus);

或其中任何一行

lo.LoadWith<Visit>(v => v.VisitSamples);
lo.LoadWith<Visit>(v => v.VisitProducts);

我做错了什么或如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题是抛出异常InvalidCastexception导致表的访问权限类型为tinyint,显然Linq To SQl有这个数据库数据类型的问题所以我将tinyint类型更改为int并且它正常工作!! !

所以这提出了一个问题,如果我不允许更改数据库设计,或者我使用数据库类型是至关重要的.IllInt是否有任何解决方法?