我有以下表格
客户表和产品表
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; }
}
客户端类
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 :(得分:0)
1:M和M:1的关系看起来就像你追求的那样 http://www.toptensoftware.com/Articles/115/PetaPoco-Mapping-One-to-Many-and-Many-to-One-Relationships
您可以定义自定义关联回调; Brad的两个表的示例(如果您的产品直接映射到客户端)看起来像这样:
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
");
我意识到你处理M:M关系所以你需要更新上面的内容来映射三个对象,但概念是相同的。关键是调用中的第三个参数(ClientProduct)代表连接的行,然后您可以直接从单个列表中引用客户端和/或产品。