2012-02-08 47 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)代表连接的行,然后您可以直接从单个列表中引用客户端和/或产品。