2012-02-08 52 views
0

我有以下表處理財產不直接映射到列的數據庫上

客戶表和產品表

ID 
Name 

ClientProduct表

ID 
ClientID 
ProductID 

產品類

private int id; 
    public int ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 
    protected string name; 

    public Product() { } 

    public Product (string name) 
    { 
     this.name = name; 
    } 

    public Product (string name) 
    { 
     this.name = name; 
    } 
    public string Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 

Client類

 private int id; 
    public int ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 
    protected string name; 

    public Client() { } 

    public Client (string name) 
    { 
     this.name = name; 
    } 

    public Client (string name) 
    { 
     this.name = name; 
    } 
    public string Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 

ClientProduct類

 protected Client client; 
    protected Product product; 

    public ClientProduct () { } 

    public ClientProduct (Client client, Product product) 
    { 
     this.client= client; 
     this.product= product; 
    } 

    public Client client  { 
     get { return client; } 
     set { client= value; } 
    } 

    public Product product  { 
     get { return product; } 
     set { product= value; } 
    } 

我怎樣才能做到在petaPOCO以下?

public static System.Collections.Generic.IList<ClientProduct> LoadForClient(Client client) 
    { 
     if (null != client) 
      return Load("ClientID = " + client.ID); 
     else 
      return null; 
    } 

,這樣我可以有所有產品的客戶端,我將在我的觀點後來被用作

private void LoadProducts(Client client) 
    { 
     Products = ClientProduct.LoadForClient(client) 
      .Select(x => x.Product.Name) 
      .OrderBy(x => x).ToArray(); 
    } 

回答

0

的1清單:M和M:1間的關係似乎是你在做什麼 http://www.toptensoftware.com/Articles/115/PetaPoco-Mapping-One-to-Many-and-Many-to-One-Relationships

您可以定義一個自定義的relator回調;布拉德對兩個表的例子(如果你的產品直接映射到客戶端)將是這個樣子:

var posts = db.Fetch<Product, Client, ClientProduct>(
    (p,c)=> { p.client_obj = c; return p; }, 
    @"SELECT * FROM Product 
    LEFT JOIN Client ON Product.clientId = Client.id ORDER BY Product.clientId 
    "); 

我知道你處理A M:M關係,所以你需要更新上述橫跨地圖三個對象,但概念是一樣的。關鍵是您的第三個參數(ClientProduct)代表連接的行,然後您可以直接從單個列表中引用客戶端和/或產品。