将函数或存储过程结果转换为LINQ的“实时”结果

时间:2010-06-01 22:17:27

标签: c# sql sql-server linq stored-procedures

是否可以通过存储过程或函数调用将在LINQ中获得的结果集转换为可以检索外键相关对象的“实时”对象集?

例如,如果我的存储过程返回一组类型为“Contact”的行(= LINQ对象),那么我似乎无法获得Contact.BillingAddress(与外键相关)。

知道如何使这项工作吗?

3 个答案:

答案 0 :(得分:1)

只需将Contacts表和BillingAddresses表拖到您的DBML设计器中,就可以正确导入Contacts和BillingAddress对象,包括关系(我假设您实际上已经这样做了,但我之所以提到它)。

接下来,在DBML中更改存储过程/函数以声明它返回Contacts类型,请参阅How to: Change the Return Type of a DataContext Method (O/R Designer)。现在,程序的返回将是一个“实时”联系人对象。

答案 1 :(得分:0)

您可以在Linq to SQL设计器中执行此操作,方法是将存储过程从服务器资源管理器拖到对象窗格右侧的“方法”窗格中。

然后,您将在datacontext上有一个方法,它将返回一种类型的ISingleResult。您可以选择覆盖此方法以映射到您希望的模型中的任何类型。

以下是一些帮助资源: http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/1667a989-08a0-402c-9358-e4637406a75f/

http://davidhayden.com/blog/dave/archive/2007/08/07/CreatingDataAccessLayerLINQToSQLStoredProceduresSupport.aspx

答案 2 :(得分:0)

您必须明确地建立表之间的关系。 LINQ to SQL设计师可能能够做到这一点,但我更喜欢编写代码,如下所示:

[Table(Name="Contact")]
public class Contact
{
   [Column(Id=true)]
   public int ContactID;
   [Column]
   public string BillingAddressID;
   private EntityRef<BillingAddress> _BillingAddress;    
   [Association(Storage="_BillingAddress", ThisKey="BillingAddressID")]
   public BillingAddress BillingAddress {
      get { return this._BillingAddress.Entity; }
      set { this._BillingAddress.Entity = value; }
   }
}

[Table(Name="BillingAddress")]
public class BillingAddress
{
   [Column(Id=true)]
   public string BillingAddressID;
   ...
   private EntitySet<Contact> _Contacts;
   [Association(Storage="_Contacts", OtherKey="BillingAddressID")]
   public EntitySet<Contact> Contacts {
      get { return this._Contacts; }
      set { this._Contacts.Assign(value); }
   }
}
相关问题