如何使用petapoco映射childs / parent类?

时间:2011-12-01 16:17:05

标签: orm petapoco

我有这些课程:

class Car {
    int ID;
    string Name;
}

class Truck : Car {
    int MaximumLoad;
}

我有这些表

Car
- ID
- Name

Truck
- CarID
- MaximumLoad

如何使用PetaPoco将我的班级映射到我的表?

3 个答案:

答案 0 :(得分:3)

如果您将Car and Truck存储在同一个表格中(TPH),您可以从Car继承Truck并对PetaPOCO源代码进行细微更改,

表车辆(ID,Discriminator,Name,MaximumLoad)

在PetaPOCO.cs中

,添加

[AttributeUsage(AttributeTargets.Class)]
public class DiscriminatorAttribute : Attribute
{
    public int Value { get; private set; }
    public DiscriminatorAttribute(object discriminator)
    {
        Value = (int)discriminator;
    }
}

protected bool IsTPHTable<T>()
{
    var t = typeof(T);
    var a = t.GetCustomAttributes(typeof(DiscriminatorAttribute), true);
    return a.Length > 0;
}

protected void AppendDiscriminator<T>(Sql sql)
{
    var t = typeof(T);
    var a = t.GetCustomAttributes(typeof(DiscriminatorAttribute), true);
    sql.Append("Where Discriminator = @0", (a[0] as DiscriminatorAttribute).Value);
}

public IEnumerable<T> Query<T>(Sql sql)
{
    if (IsTPHTable<T>())
        AppendDiscriminator<T>(sql);
    return Query<T>(default(T), sql);
}

// also similar AppendDiscriminator() for Update an Delete.

然后在你的Car.cs和Truck.cs中,你可以编写/生成这样的代码,

public enum VehicleType:int
{
    Car,
    Truck
}

[TableName("Vehicle")]
[Discriminator(VehicleType.Car)]
public class Car  
{
    [Column] 
    public int ID {get; set;}
    [Column]
    public string Name {get; set;}

    public Car()
    {
        //this.Discriminator = VehicleType.Car;
    }
    public static new Car SingleOrDefault(object primaryKey) { return repo.SingleOrDefaultById<Car>(primaryKey); }
    //...
}

[Discriminator(VehicleType.Truck)]
public class Truck:Car  
{
    [Column] 
    public double MaximumLoad {get;set;}

    public Truck()
    {
        //this.Discriminator = VehicleType.Truck;
    }   
    public static new Truck SingleOrDefault(object primaryKey) { return repo.SingleOrDefaultById<Truck>(primaryKey); }
    //...
}

答案 1 :(得分:2)

要读取卡车记录,我会创建一个结合了两个表的卡车视图。或者看看Schotime的多个结果集:

http://schotime.net/blog/index.php/2011/11/20/petapoco-multiple-result-sets/

对于写入,我猜你在问“如何在一次操作中写入2个表”。在我的头脑中,我可能会说我只会执行2次写入。我认为Petapoco将忽略不映射的字段,这样您就可以使用卡车对象进行两次写入。

可能很容易出错,因为我没有测试过这个。

答案 2 :(得分:0)

我认为(尽管没有测试过)如果你这样做了......

repo.Fetch<Truck>(";Select car.*, truck.maximumload from car left join truck on car.id = truck.carid");

repo.Fetch<Truck>(";Select car.*, truck.maximumload from car left join truck on car.id = truck.carid where truck.carid = @0", truckid);

我可能会打电话给我的基础车而不是汽车,但那只是我。

希望有帮助吗?