Reputation: 57
Not able to figure out the proper mapping for below table.
Table: ItemSale {ItemCode, SaleDate, Qty, SaleCode}
ItemCode and SaleDate are composite key.
SaleCode is a derived column, generated from the combination of ItemCode and SaleDate column.
Table: ItemSaleDetail {SaleCode, Agent}
SaleCode is a primary key and foreign key from ItemSale table for SaleCode column.
Entities and their mappings are given below.
ItemSale
public class ItemSale
{
public virtual string ItemCode { get; set; }
public virtual string Date { get; set; }
public virtual string SaleCode { get; set; }
public virtual ItemSaleDetail SaleDetail { get; set; }
}
public class ItemSaleMap : ClassMap<ItemSale>
{
public ItemSaleMap()
{
Table("ItemSale");
CompositeId()
.KeyReference(x => x.ItemCode, "ItemCode")
.KeyProperty(x => x.Date, "SaleDate");
HasOne(x => x.SaleDetail).Cascade.All();
}
}
ItemSaleDetail
public class ItemSaleDetail
{
public virtual string ItemSaleCode { get; set; }
public virtual string Agent { get; set; }
public virtual ItemSale SaleParent { get; set; }
}
public class ItemSaleDetailMap : ClassMap<ItemSaleDetail>
{
public ItemSaleDetailMap()
{
Table("ItemSaleDetail");
Id(x => x.ItemSaleCode).GeneratedBy.Foreign("SaleParent");
Map(x => x.Agent, "Agent");
HasOne(x => x.SaleParent).Constrained();
}
}
I have given above the basic one to one mapping being used in traditional way which I know is wrong in this case. Please suggest how to provide the proper mapping in this case. Also if derived column SaleCode to be generated by the application, how can we have this property in my entity. As it is not allowed have multiple mapping for a single column.
Upvotes: 2
Views: 2813
Reputation: 123861
OK, with assignable ID we can do it like this. Firstly we should be sure, that the ID is assigned, so we can adjust the getter of the <id>
ItemSaleCode
like this:
public class ItemSaleDetail
{
string _itemSaleCode;
public virtual string ItemSaleCode
{
get { return _itemSaleCode ?? SaleParent.SaleCode ; }
set { _itemSaleCode = value; }
}
Now, we need mapping like this:
<id name="ItemSaleCode" column="SaleCode" type="String" generator="assigned" />
<one-to-one name="SaleParent" class="ItemSale"
constrained="true" property-ref="SaleCode" />
...
...
Which in Fluent should be like this:
public ItemSaleDetailMap()
{
...
Id(x => x.ItemSaleCode)
.CustomType<String>()
.Column("SaleCode")
.GeneratedBy.Assigned();
HasOne(x => x.SaleParent)
.ProeprtyRef("SaleCode")
.Constrained();
}
public ItemSaleMap()
{
References(x => x.SaleDetail)
.Column("SaleCode")
.Unique()
.Cascade.All();
Map(x => x.SaleCode)
.Column("SaleCode")
.Not.Update()
.Not.Insert()
}
But again, Surrogate INT or LONG keys are the way I would go for sure...
Upvotes: 2