Ormlite中的自定义参考命名约定

时间:2019-03-30 00:33:01

标签: servicestack ormlite-servicestack

是否可以更改引用和外键的默认 {PropertyReference} Id 命名约定?

例如,我要这样做:

public class Customer
{
    [References(typeof(CustomerAddress))]
    public int Id_PrimaryAddress { get; set; } // with a prefix

    [Reference]
    public CustomerAddress PrimaryAddress { get; set; }
}

代替:

public class Customer
{
    [References(typeof(CustomerAddress))]
    public int PrimaryAddressId { get; set; } // standard

    [Reference]
    public CustomerAddress PrimaryAddress { get; set; }
}

谢谢

1 个答案:

答案 0 :(得分:1)

您无法全局更改OrmLite's Reference Conventions的代码约定,但可以使用[Alias("DbColumnName")]将其映射到其他基础RDBMS表列。

具有属性的替代约定

您还可以像示例一样使用Foreign Key and References Attributes来覆盖约定,例如您可以play with this Live Example on Gistlyn

public class CustomerAddress 
{
    [AutoIncrement]
    public int Id { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
}

public class Customer
{
    [AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }

    [References(typeof(CustomerAddress))]
    public int Id_PrimaryAddress { get; set; } // with a prefix

    [Reference]
    public CustomerAddress PrimaryAddress { get; set; }
}

db.CreateTable<Customer>();
db.CreateTable<CustomerAddress>();

var customer = new Customer
{
    Name = "The Customer",
    PrimaryAddress = new CustomerAddress {
        Address = "1 Home Street",
        Country = "US"
    },
};

db.Save(customer, references:true);

可以在哪里加载它及其引用,并使用以下命令查看它:

var c = db.LoadSelect<Customer>(x => x.Name == "The Customer");

c.PrintDump();

哪个会输出:

[
    {
        Id: 1,
        Name: The Customer,
        Id_PrimaryAddress: 1,
        PrimaryAddress: 
        {
            Id: 1,
            Address: 1 Home Street,
            Country: US
        }
    }
]