[英]FluentNHibernate mapping of composite foreign keys
我有一個現有的數據庫架構,希望用Fluent.NHibernate替換自定義數據訪問代碼。 由於數據庫模式已經存在於運輸產品中,因此無法更改。 並且優選的是,域對象不改變或僅改變很小。
我在映射用以下表結構說明的一種異常模式結構時遇到了麻煩:
CREATE TABLE [Container] (
[ContainerId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Container] PRIMARY KEY (
[ContainerId] ASC
)
)
CREATE TABLE [Item] (
[ItemId] [uniqueidentifier] NOT NULL,
[ContainerId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY (
[ContainerId] ASC,
[ItemId] ASC
)
)
CREATE TABLE [Property] (
[ContainerId] [uniqueidentifier] NOT NULL,
[PropertyId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Property] PRIMARY KEY (
[ContainerId] ASC,
[PropertyId] ASC
)
)
CREATE TABLE [Item_Property] (
[ContainerId] [uniqueidentifier] NOT NULL,
[ItemId] [uniqueidentifier] NOT NULL,
[PropertyId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Item_Property] PRIMARY KEY (
[ContainerId] ASC,
[ItemId] ASC,
[PropertyId] ASC
)
)
CREATE TABLE [Container_Property] (
[ContainerId] [uniqueidentifier] NOT NULL,
[PropertyId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_Container_Property] PRIMARY KEY (
[ContainerId] ASC,
[PropertyId] ASC
)
)
現有的領域模型具有以下類結構:
Property類包含其他代表屬性名稱和值的成員。 ContainerProperty和ItemProperty類沒有其他成員。 它們僅存在以識別財產的所有者。 Container和Item類具有分別返回ContainerProperty和ItemProperty的集合的方法。 此外,Container類具有一個方法,該方法返回對象圖中所有Property對象的集合。 我最好的猜測是,這是一種便捷方法,還是一種從未刪除過的傳統方法。
業務邏輯主要與Item(作為聚合根)一起使用,並且僅在添加或刪除Items時與Container一起使用。
我嘗試了幾種技術來映射它,但是沒有用,所以除非有人要求,否則我不會在這里包括它們。 您將如何映射?
映射應如下所示:
public sealed class CategoryMap : ClassMap<Category>
{
public CategoryMap()
{
Table("Categories");
CompositeId()
.KeyProperty(c => c.ItemId, "ItemId")
.KeyProperty(c => c.CategoryId, "CategoryId");
}
}
注意:
--
public class Category
{
public virtual int ItemId { get; set; }
public virtual int CategoryId { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Category)) return false;
return Equals((Category) obj);
}
public virtual bool Equals(Category other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.ItemId == ItemId && other.CategoryId == CategoryId;
}
public override int GetHashCode()
{
unchecked
{
return (ItemId*397) ^ CategoryId;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.