Loading

Entity Framwork one to one problem

这里先感谢dudu的研究,有了非常好的样例代码!!~~

贴上连接,如果没有看过的同学请先阅读:

http://www.cnblogs.com/dudu/archive/2011/07/07/entity_framework_one_to_one.html

问题:

//针对“一对一”关系的设置
modelBuilder.Entity<BlogSite>().HasRequired(b => b.BlogUser).
WithRequiredDependent().Map(conf => conf.MapKey("UserID"));

//出现如下恶心的脚本

SELECT
[Extent1].[BlogID] AS [BlogID],
[Extent1].[BlogApp] AS [BlogApp],
[Extent1].[IsActive] AS [IsActive],
[Join1].[UserID1] AS [UserID],
[Join1].[Author] AS [Author],
[Join3].[BlogID] AS [BlogID1]
FROM   [dbo].[BlogSite] AS [Extent1]
LEFT OUTER JOIN  (SELECT [Extent2].[UserID] AS [UserID1], [Extent2].[Author] AS [Author]
    FROM  [dbo].[BlogUser] AS [Extent2]
    LEFT OUTER JOIN [dbo].[BlogSite] AS [Extent3] ON [Extent2].[UserID] = [Extent3].[UserID] ) AS [Join1]
    ON [Extent1].[UserID] = [Join1].[UserID1]
LEFT OUTER JOIN  (SELECT [Extent4].[UserID] AS [UserID2], [Extent5].[BlogID] AS [BlogID]
    FROM  [dbo].[BlogUser] AS [Extent4]
    LEFT OUTER JOIN [dbo].[BlogSite] AS [Extent5]
    ON [Extent4].[UserID] = [Extent5].[UserID] ) AS [Join3] ON [Extent1].[UserID] = [Join3].[UserID2]
WHERE 1 = [Extent1].[IsActive]

 

dudu的解决办法:

WithMany()

dudu的解决方案无疑可以满足大家的需求,但是看着这个很难跟一对一联系起来,不过话说回来,在一对多中也是这个脚本。其实一对一本质是就是把概念上一张表在物理上分为两张表。

网上看了一句话:

For one-to-one relationships, EF expects that the tables are using the same primary key. And really, if it's a true one-to-one they probably should.

说的真好,但是实际上大家在设计库,不管什么原因总有跟设计原则相违背的地方,我们不可能重新设计表等恐怖的操作。在dudu的示例中BlogSite和BlogUser 共有字段UserId,那么咱就在Ef中指定如下

    modelBuilder.Entity<BlogUser>().ToTable("BlogUser");
modelBuilder.Entity<BlogUser>().HasKey(u => u.UserID);

modelBuilder.Entity<BlogSite>().ToTable("BlogSite");
modelBuilder.Entity<BlogSite>().HasKey(b => b.UserID);
一对一:
modelBuilder.Entity<BlogSite>().HasRequired(b => b.BlogUser).
WithRequiredDependent();
输出脚本:

SELECT
[Extent1].[BlogID] AS [BlogID],
[Extent1].[BlogApp] AS [BlogApp],
[Extent1].[IsActive] AS [IsActive],
[Extent1].[UserID] AS [UserID],
[Extent2].[UserID] AS [UserID1],
[Extent2].[Author] AS [Author]
FROM [dbo].[BlogSite] AS [Extent1]
INNER JOIN [dbo].[BlogUser] AS [Extent2] ON [Extent1].[UserID] = [Extent2].[UserID]
WHERE 1 = [Extent1].[IsActive]

 

Done

posted @ 2011-07-14 11:57  today4king  阅读(403)  评论(0编辑  收藏  举报