开发者

How do I map a custom Value Object in Linq-to-sql?

We have a Price value object, that we want to map to a decimal SQL field via Linq-to-Sql.

We use Linq-to-SQL's attributes directly (that is... we don't use the Linq-to-Sql designer).

I want to write something like this:

[Table]
public class Product: Aggregate
{
    //...
    [Column]
    public string Name {get; set;}

    [Column]
    public Price Price {get; set;}

    [Column]
    public Price? GoldCustomerPrice {get; set;}

    //...
 }

In the sample above Linq-to-sql automatically detects that Name should be mapped to a VarChar. But how do do I tell it to map Price.ExcludingVat to a decimal and GoldCustomerPrice.Value.ExcludingVat to a decimal field allowing null?

This is how I do it right now. Very verbose.

[Table]
public class Product: Aggregate
{
    //...
    [Column]
    public string Name {get; set;}

    [Column(Name = "Price")]
    decimal priceExcludingVat;

    public Price Price
    {
        get { return new Price(priceExcludingVat) }
        set { priceExcludingVat = value.ExcludingVat ; }
    }

    [Column(Name = "GoldCustomerPrice")]
    private decimal? goldCustomerPriceExcludingVat;

    public Price? GoldCustomerPri开发者_如何学Goce 
    {
        get
        {
            if(goldCustomerPriceExcludingVat.HasValue)
                return new Price(goldCustomerPriceExcludingVat.Value)
            else
                return (Price?) null;
        }
        set
        { 
            if (value == null)
                goldCustomerPriceExcludingVat = null;
            else
                goldCustomerPriceExcludingVat = value.Value.ExcludingVat;
        }
    }
    //...
 }

And in case you are wondering the Price value object looks like this:

public struct Price 
{
    public Price(decimal priceExcludingVat) : this()
    {
        ExcludingVat = priceExcludingVat;
        VatRate = Settings.VatRate;
    }

    public decimal ExcludingVat { get; private set; }

    public decimal VatRate{ get; set;}

    public decimal Vat
    {
        get { return ExcludingVat * VatRate; }
    }

    public decimal IncludingVat
    {
        get { return ExcludingVat * Vat; }
    }

    //... a lot of operator overloads
}


Is this what you're after?

[Column(Storage="Price", DbType="float NOT NULL")]


Doesn't it work with operator overloading, where you implement one for decimals?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜