Thanks to dudu's research, we have a very good sample code !!~~
Paste the connection. If you have not read the connection, read it first:
Http://www.cnblogs.com/dudu/archive/2011/07/07/entity_framework_one_to_one.html
Problem:
// Set the "one-to-one" Relationship
ModelBuilder. Entity <BlogSite> (). HasRequired (B => B. BlogUser ).
WithRequiredDependent (). Map (conf => conf. MapKey ("UserID "));
// The following disgusting script appears
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 solution:
Withtasks ()
Dudu's solution can undoubtedly meet everyone's needs, but it's hard to get in touch with one-to-one. However, this script is also used in one-to-many scenarios. In fact, one-to-one mechanism is to physically divide a table into two tables.
I read a sentence online:
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 probablyShocould.
That's really good. But in fact, no matter what the reason is, there is always something contrary to the design principles. We cannot redesign tables or other horrible operations. In the dudu example, BlogSite and BlogUser have a common field UserId, so you can specify the following in 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);
One to one:
modelBuilder.Entity<BlogSite>().HasRequired(b => b.BlogUser).
WithRequiredDependent();
Output script:
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