开发者

NHibernate: map multiple columns into a single collection

开发者 https://www.devze.com 2023-01-14 09:32 出处:网络
Suppose I have a ta开发者_C百科ble: ID(pk) | HOME_EMAIL | WORK_EMAIL | OTHER_EMAIL -------------------------------------------------

Suppose I have a ta开发者_C百科ble:

 ID(pk) | HOME_EMAIL | WORK_EMAIL | OTHER_EMAIL
-------------------------------------------------

and the .NET classes

class A {
    int id;
    List<MyEmail> emails;
}

class MyEmail {
    string email;
}

I suppose there's no way to map those (multiple) columns into a single collection in NHibernate, or is there? :)

It's come to a point that we'd rather not tinker with the database schema anymore so we can't do much with the database, if that helps.


I would suggest working with Interfaces so you could do something like this

 interface IUser
{
    int Id {get; set;}
    IEnumerable<string> Emails {get;}
}

class MyUser : IUser
{
    public int Id {get; set;}
    public IEnumerable<string> Emails
    {
        get
        {
            return new [] { SomeEmail, SomeOtherEmail };
        }
    }

    public string SomeEmail { get; set; }
    public string SomeOtherEmail { get; set; }
}

Your application can expect an IUser and not care where we got the list of emails. You would map MyUser in NH, while the application does not (and should not) care about the actual implementation.


If it doesn't have to be a collection, but could be a custom type instead, say EmailAddresses which contains three properties:

public class EmailAddresses
{
    public virtual string Home { get; set; }
    public virtual string Work { get; set; }
    public virtual string Other { get; set; }
}

You could use a component to map the three columns into the three properties of this object as a single property on the parent:

public class MyUser
{
    ...
    public virtual EmailAddresses { get; set; }
}

You can map these in NHibernate using components or if you're using Fluent NHibernate with the ComponentMap<T> classmap (automapper can't do components).


There is a feature that's very close to what you want, <dynamic-component>

The documentation at http://nhibernate.info/doc/nh/en/index.html#components-dynamic should get you started.

0

精彩评论

暂无评论...
验证码 换一张
取 消