我无法让 NHibernate 映射 AccountCode
Beneficiary
的列表 AccountCode
这种一对一关系中的列(每个 Account
有一个 Beneficiary
,每个 Beneficiary
有一个 Account
)。
类:
public class Account
{
...
public virtual string Name { get; protected set; }
public virtual string Code { get; protected set; }
}
public class Beneficiary
{
...
public virtual int Id { get; set; }
public virtual string Name { get; protected set; }
public virtual Account Account { get; protected set; }
public virtual BeneficiaryGroup Group { get; protected set; }
}
SQL:
CREATE VIEW dbo.Account AS
SELECT DISTINCT RTRIM(LTRIM(ACCNT_NAME)) AS Name,
RTRIM(LTRIM(ACCNT_CODE)) AS Code
FROM myremoteserver.schema.tablename
WHERE ACCNT_TYPE NOT IN ('B', 'P')
CREATE TABLE dbo.Beneficiary
(
Id INT IDENTITY(1,1) NOT NULL,
BeneficiaryGroupId INT NOT NULL CONSTRAINT FK_Beneficiaries_BeneficiaryGroup FOREIGN KEY REFERENCES dbo.BeneficiaryGroup (Id),
Name VARCHAR(100) NOT NULL,
AccountCode VARCHAR(100) NOT NULL,
CONSTRAINT PK_Beneficiary PRIMARY KEY (Id)
)
尝试使用 HasMany
时和不同的变体,NHibernate 尝试加入 Beneficiary.Id
柱子。
我尝试了 Map
的不同变体, References
, Join
(它告诉我连接已经存在)和 HasMany
(失败了,因为关系确实是一对一的)。
如何让 NHibernate 将这两个类正确映射到它们的列?
在尝试不同的流畅映射时,在我的 IAutoMappingOverride<Beneficiary>
,会发生以下情况:
mapping.HasOne(b => b.Account);
mapping.HasOne(b => b.Account).PropertyRef(sa => sa.Code);
mapping.HasOne(b => b.Account).PropertyRef(sa => sa.Code).ForeignKey("none");
生成的 SQL 使用 Beneficiary.Id
字段而不是 Beneficiary.AccountCode
. (在你问之前,我使用“none”,因为 Account
是一个 View ,它不能有键)。
mapping.Join("AccountCode", x => x.References(y => y.Account));
mapping.Join("Account", b => b.KeyColumn("AccountCode"));
结果为 Tried to add join to table 'Account' when already added.
.
还有:
mapping.Map(b => b.Account, "AccountCode");
mapping.Map(b => b.Account).ReadOnly().Column("AccountCode");
结果:
Could not determine type for: .Account, , Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, for columns: NHibernate.Mapping.Column(AccountCode)
mapping.References(b => b.Account).Column("Code");
结果为 Invalid column name 'Code'.
.
还有:
mapping.References(b => b.Account).Column("AccountCode");
mapping.References(b => b.Account).Column("AccountCode").Access.Property();
覆盖我所有的IReferenceConvention
覆盖(将某些类映射为具有 <class name>Code
键列)。
尝试 HasMany
时:
mapping.HasMany<Account>(b => b.Account).KeyColumn("AccountCode");
Custom type does not implement UserCollectionType: .Account
最佳答案
// in BeneficiaryMapping
mapping.References(b => b.Account)
.Column("AccountCode" /* of Beneficiary table*/)
.PropertyRef(a => a.Code); // use the Column of Code as the joincolumn in Account table
关于view - 映射以查看自定义字段名称 - 一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12975707/