首先添加表和數據:
--I use db Breaz, you use whatever you require
USE [Breaz]
GO
/****** Object: Table [dbo].[table1] Script Date: 5/4/2017 12:20:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[table1](
[Id] [int] IDENTITY(1,1) NOT NULL,
[field1] [varchar](10) NULL,
[field2] [varchar](10) NULL,
[field3] [varchar](10) NULL,
[field4] [varchar](10) NULL,
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[table2] Script Date: 5/4/2017 12:20:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[table2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Field4Default] [varchar](10) NULL,
CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[table1] ON
GO
INSERT [dbo].[table1] ([Id], [field1], [field2], [field3], [field4]) VALUES (1, N'f1', N'f2', N'f3', N'f4')
GO
INSERT [dbo].[table1] ([Id], [field1], [field2], [field3], [field4]) VALUES (2, N'seconda', N'secondb', N'secondc', NULL)
GO
SET IDENTITY_INSERT [dbo].[table1] OFF
GO
SET IDENTITY_INSERT [dbo].[table2] ON
GO
INSERT [dbo].[table2] ([Id], [Field4Default]) VALUES (3, N'DefaultV')
GO
SET IDENTITY_INSERT [dbo].[table2] OFF
GO
添加EDMX:右鍵點擊Models文件夾,並添加ADO.NET實體數據模型。將其命名爲table1並單擊確定,突出顯示從數據庫生成,因此單擊下一步。點擊新建連接。輸入服務器名稱。使用Windows身份驗證或使用SQL服務器身份驗證(憑據),如果後者,請單擊保存我的密碼。從下拉菜單中選擇數據庫。點擊確定。等待點擊'是的,包括敏感..',如果你沒有Windows認證。 '保存實體連接..'下面的連接複製到剪貼板。點擊下一步。在表格下,選擇table1和table2。點擊完成。然後點擊確定以獲得接下來的兩個提示(等待它們),然後關閉gui設計器。
這是你的控制器。
public class HomeController : Controller
{
public ActionResult Index63()
{
var table1List = new List<table1>();
//instead of BreazEntities18, use the name you copied to the clipboard
//or lick on table1.context.cs to get the name
using (BreazEntities18 entity = new BreazEntities18())
{
var q = entity.table1.Select(r => new
{
field1 = r.field1,
field2 = r.field2,
field3 = r.field3,
field4 = r.field4 == null ? (entity.table2.Select(s => s.Field4Default).FirstOrDefault())
: r.field4
}
).ToList();
}
return View();
}
您投了票的答案不起作用。請參閱其他答案。你能否告訴我,如果這個方法有效,並告訴我你是否希望我把答案弄清楚。 – kblau
我在下面更新了我的答案,以便它包含一個選擇。我並不是說Ashiquzzaman沒有解決問題,但我無法讓他/她的解決方案工作。 – kblau
你可以做一個連接而不是子查詢嗎? – Jasen