Linq to sql 如何将Linq中的自定义值对象映射到sql?
我们有一个Price-value对象,希望通过Linq-to-SQL映射到十进制SQL字段 我们直接使用LINQtoSQL的属性(也就是说,我们不使用LINQtoSQL设计器) 我想写这样的东西:Linq to sql 如何将Linq中的自定义值对象映射到sql?,linq-to-sql,Linq To Sql,我们有一个Price-value对象,希望通过Linq-to-SQL映射到十进制SQL字段 我们直接使用LINQtoSQL的属性(也就是说,我们不使用LINQtoSQL设计器) 我想写这样的东西: [Table] public class Product: Aggregate { //... [Column] public string Name {get; set;} [Column] public Price Price {get; set;}
[Table]
public class Product: Aggregate
{
//...
[Column]
public string Name {get; set;}
[Column]
public Price Price {get; set;}
[Column]
public Price? GoldCustomerPrice {get; set;}
//...
}
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
}
在上面的示例中,LINQtoSQL自动检测名称应该映射到VarChar。但是,如何让它将Price.excludingwat映射到一个十进制字段,并将GoldCustomerPrice.Value.excludingwat映射到一个允许null的十进制字段
我现在就是这样做的。非常冗长
[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? GoldCustomerPrice
{
get
{
if(goldCustomerPriceExcludingVat.HasValue)
return new Price(goldCustomerPriceExcludingVat.Value)
else
return (Price?) null;
}
set
{
if (value == null)
goldCustomerPriceExcludingVat = null;
else
goldCustomerPriceExcludingVat = value.Value.ExcludingVat;
}
}
//...
}
如果您想知道Price-value对象是这样的:
[Table]
public class Product: Aggregate
{
//...
[Column]
public string Name {get; set;}
[Column]
public Price Price {get; set;}
[Column]
public Price? GoldCustomerPrice {get; set;}
//...
}
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
}
这就是你想要的吗
[Column(Storage="Price", DbType="float NOT NULL")]
它不适用于运算符重载吗?在重载中,您实现了一个小数?Price对象不能转换为十进制/浮点,因此如果这样做可行,我必须编写如下内容:[Column(Storage=“Price.ExcludingVat”,DbType=“float not NULL”)]。。。这不管用啊,我明白你的意思了。不含增值税的价格是否作为列存储在db中?还是计算?它存储在数据库中。它只是一个普通值对象(DDD),我们希望映射它。在NHibernate中,这非常简单,但我想不可能让Linq to SQL与值对象一起工作。Esp第4版。