2010-06-21 68 views
1

我有如下表:實體框架:如何與2個表

概況:

簡檔(主鍵)
摘要名稱等

聯繫人:

的ContactID(主Key)
ProfileFromID(外鍵)
ProfileToID(外鍵)
消息varchar(50)等

配置文件可能有許多聯繫消息。因此,給定的消息將具有誰發送了該消息以及該消息被髮送給誰。

我很難在兩張表之間建立關係。它很容易將Profile.ProfileID連接到Contact.ProfileIDFrom。

但我也想Profile.ProfileID連接到Contact.ProfileIDTo

所以......後來我想查詢在我的實體如下...

Profile.MessageFrom會給我簡介名稱和... Profile.MessageTo會給我個人資料名稱....

我想能夠提取profileIDFrom和ProfileIDTo配置文件名稱。

我不知道如何連接2個表。

回答

3

你必須在數據庫中創建兩個外鍵別名:

-- Creating foreign key on [ProfileFromId] in table 'Contacts' 
ALTER TABLE [dbo].[Contacts] 
ADD CONSTRAINT [FK_ProfileContactFrom] 
    FOREIGN KEY ([ProfileFromId]) 
    REFERENCES [dbo].[Profiles] 
     ([ProfileId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION; 

-- Creating non-clustered index for FOREIGN KEY 'FK_ProfileContactFrom' 
CREATE INDEX [IX_FK_ProfileContactFrom] 
ON [dbo].[Contacts] 
    ([ProfileFromId]); 
GO 
-- Creating foreign key on [ProfileToId] in table 'Contacts' 
ALTER TABLE [dbo].[Contacts] 
ADD CONSTRAINT [FK_ProfileContactTo] 
    FOREIGN KEY ([ProfileToId]) 
    REFERENCES [dbo].[Profiles] 
     ([ProfileId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION; 

-- Creating non-clustered index for FOREIGN KEY 'FK_ProfileContactTo' 
CREATE INDEX [IX_FK_ProfileContactTo] 
ON [dbo].[Contacts] 
    ([ProfileToId]); 
GO 

添加兩個導航屬性中的聯繫實體您模型。例如ProfileFromProfileTo

您可以使用預先加載到去做查詢是這樣的:

using (var ctx = new TestModelContainer()) 
     { 
      foreach (Contact contact in ctx.Contacts 
              .Include("ProfileFrom") 
              .Include("ProfileTo")) 
        { 
         Console.WriteLine("From: {0}, to: {1}, Message: \"{2}\"", contact.ProfileFrom.ProfileName, contact.ProfileTo.ProfileName, contact.Message); 
        } 
     } 
+0

非常感謝你!!!! – 2010-06-21 13:37:51

0

你必須從聯繫人2(外鍵)關係 - 檔(* - 1)

但據ORM-S去,你可能需要創建2個以上的不同實體 - 這(種?)根據是你的用例 (我不熟悉的實體framewrk)