EF双向一对一中的坑
EF版本 6.0
在项目中双向一对一关系是普遍存在的,如果不仔细检查,并不容易发现这个坑
下面新建两个类(假设这两个类是一对一的关系)对应实体都设置为可延迟加载
映射关系为:
再建一个数据访问类:
运行下面查询语句:
TestContext db = new TestContext(); var list = db.QuerySchool.ToList();
正常情况下,生成的查询语句应该只查询SchoolInfo表,但是生成sql语句却是这样:
SELECT [Extent1].[Sid] AS [Sid], [Extent1].[SchoolName] AS [SchoolName], [Extent2].[Id] AS [Id] FROM [dbo].[SchoolInfo] AS [Extent1] LEFT OUTER JOIN [dbo].[ClassInfo] AS [Extent2] ON [Extent1].[Sid] = [Extent2].[SchoolId]
进行了一个表联查,明明没有查询ClassInfo表这里却进行了关联(问题1)
下面修改下查询语句
var list = db.QuerySchool.Select(x => new { SId = x.Sid, SchoolName = x.SchoolName }).ToList();
只查询出ID和SchoolName,生成sql语句如下:
SELECT [Extent1].[Sid] AS [Sid], [Extent1].[SchoolName] AS [SchoolName] FROM [dbo].[SchoolInfo] AS [Extent1]
这次却是正常的
现在查询ClassInfo表:
var list = db.QueryClass.ToList();
生成sql语句如下:(问题2)
SELECT [Extent1].[Id] AS [Id], [Extent1].[SchoolName] AS [SchoolName], [Extent1].[ClassName] AS [ClassName], [Extent1].[SchoolId] AS [SchoolId] FROM [dbo].[ClassInfo] AS [Extent1]
可以看到SQL语句并未像SchoolInfo表一样出现表联查语句
疑问:
HasRequired(x => x.School).WithRequiredDependent(x => x.ClassInfo).Map(map => map.MapKey("SchoolId")).WillCascadeOnDelete(true);
ClassInfo必须有SchoolInfo,SchoolInfo又依赖ClassInfo,二者是生死存亡的关系,缺一不可,可是这样无法解释问题1和问题2
当关系为单向一对一关系时查询是正常的,不会出现表联查现象