从多个表

时间:2015-05-19 06:36:42

标签: c# sql sql-server linq listview

我需要从两个(或更多)表创建一个列表视图(我正在使用sql server)。 我的项目是关于公寓租赁。

我有一张所有者表:

[OwnerID]     INT        IDENTITY (1, 1)    NOT NULL,
[Name]        NVARCHAR (50) NOT NULL,
[Username]    NVARCHAR (50) NOT NULL,
[Password]    NVARCHAR (50) NOT NULL,
[Phone]       NVARCHAR (50) NOT NULL,
[Mail]        NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (50) NOT NULL,
[Image]       IMAGE         NULL,

我有一张公寓桌子:

[ApartmentID]     INT           NOT NULL,
[Address]         NVARCHAR (50) NOT NULL,
[OwnerID]         INT           NULL,
[AgentID]         INT           NULL,
[apartmentTypeID] INT           NOT NULL,
[Floor]           INT           NOT NULL,
[Rooms]           INT           NOT NULL,
[AgencyFees]      INT           NULL,
[Immediately]     INT           NOT NULL,
[DateOfEntrance]  DATETIME      NULL,
[Price]           INT           NOT NULL,
[Description]     NVARCHAR (50) NOT NULL,
[Image]           IMAGE         NULL,
[CityID]          INT           NOT NULL,

我想在 listview 中显示公寓表的数据,但是我想从Owner表中显示ownerName而不是字段“ownerID”。我知道我需要在某种程度上使用linq ......

如果有人可以告诉我该怎么做,我会很感激:-) 谢谢!

1 个答案:

答案 0 :(得分:2)

考虑加入这两个表,比如查看此查询,

SELECT 
t1.[ApartmentID],
t1.[Address],
t2.[Name],
t1.[AgentID],
t1.[apartmentTypeID],
t1.[Floor],
t1.[Rooms],
t1.[AgencyFees],
t1.[Immediately],
t1.[DateOfEntrance],
t1.[Price],
t1.[Description],
t1.[Image],
t1.[CityID]
FROM
Apartment AS t1 INNER JOIN Owner AS t2
ON t1.[OwnerID]=t2.[OwnerID];

这是LINQ,

var q = (from t1 in Apartment join t2 in Owner on t1.OwnerID equals t2.OwnerID
 select new { 
    t1.ApartmentID,
    t1.Address,
    t2.Name,
    t1.AgentID,
    t1.apartmentTypeID,
    t1.Floor,
    t1.Rooms,
    t1.AgencyFees,
    t1.Immediately,
    t1.DateOfEntrance,
    t1.Price,
    t1.Description,
    t1.Image,
    t1.CityID
 }).ToList();

希望它有所帮助,谢谢。