2

我正在尝试在 FNH 中映射以下表格/实体,但似乎无处可去!

**Tables**
Contacts
    ID (PK - int - generated)
    ...

PhoneTypes
    ID (PK - varchar - assigned) (e.g. MOBILE, FAX)

ContactPhones
    ContactRefId    (PK - FK to Contacts)
    PhoneTypeRefId  (PK - FK to PhoneTypes)
    ...

(我应该注意我也在使用 S#arp Architecture 框架)

**Entities**
public class Contact : Entity
{
    (The ID property is defined in the Entity base class and is type int)

    public virtual ICollection<ContactPhone> PhoneNumbers { get; set; }
}

public class PhoneType : EntityWithTypedId<string>, IHasAssignedId<string>
{
    (The ID property is defined in the base class and is type string)

    ....
}

public class ContactPhone : EntityWithTypedId<ContactPhoneId>, IHasAssignedId<ContactPhoneId>
{
    public virtual Contact Contact { get; set; }

    public virtual PhoneType PhoneType { get; set; }
    ....
}

我读到在使用复合 id 时建议将复合 id 分成不同的类。 休眠复合键

public class ContactPhoneId : EntityWithTypedId<ContactPhoneId>, IHasAssignedId<ContactPhoneId>
{
    public virtual Contact Contact { get; set; }

    public virtual PhoneType PhoneType { get; set; }
}
...I could just make this class serializable and override 
Equals and GetHashCode myself instead of using the S#arp Arch base class.

我已经尝试了很多映射组合,以至于我现在完全糊涂了。

这是我最近拍的:

public class ContactMap : IAutoMappingOverride<Contact>
{
    public void Override(AutoMapping<Contact> mapping)
    {
        mapping.HasMany<ContactPhone>(x => x.PhoneNumbers)
            .KeyColumns.Add("ContactRefId")
            .KeyColumns.Add("PhoneTypeRefId")
            .AsSet()
            .Inverse()
            .Cascade.All();
    }
}


public class PhoneTypeMap : IAutoMappingOverride<PhoneType>
{
    public void Override(AutoMapping<PhoneType> mapping)
    {
        mapping.Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
    }
}


public class ContactPhoneMap : IAutoMappingOverride<ContactPhone>
{
    public void Override(AutoMapping<ContactPhone> mapping)
    {
        mapping.Table("ContactPhones");
        mapping.CompositeId<ContactPhoneId>(x => x.Id)
            .KeyReference(y => y.Contact, "ContactRefId")
            .KeyReference(y => y.PhoneType, "PhoneTypeRefId");
    }
}  

我在尝试生成映射时抛出了许多异常,其中最新的是:

Foreign key (FK672D91AE7F050F12:ContactPhones [ContactRefId, PhoneTypeRefId])) 
must have same number of columns as the referenced primary key (Contacts [Id])

有没有人看到我做错了什么明显的事情?我是 NH 和 FNH 的新手,这在这篇文章中可能很明显。:-) 另外,有没有人在使用 S#arp 架构时使用过这样的复合 ID?什么是最佳实践(除了使用代理键:-))?

非常感谢……对这篇长文感到抱歉。

4

1 回答 1

0

我也有多对多的关系。我有这样的设置:

mapping.HasManyToMany(x => x.Artists).Cascade.All().Inverse().Table("ArtistImages");

ArtistImages 表具有表 Artists 和 Images 的主键。

于 2010-07-06T18:36:37.290 回答