如何使用多个表创建一个到至少一个流畅的映射?

时间:2012-05-03 14:01:51

标签: nhibernate fluent-nhibernate

我有一个旧设计的数据库架构,我想用Fluent-Nhibenrate映射它。

架构看起来像这样:

Table:Users
ID Number PK

Table:Kiosk
User_ID Number PK, FK -> Users.ID
Xml Varchar

Table:Email
User_ID Number PK, FK -> Users.ID
Update_Date Date

我希望使用看起来像这样的映射对象来实现:

public class User
{
    private virtual Email _email {get;set;}

    public virtual int Id {get;set;}
    public virtual string Email
    {
        get
        {
            return _email.Email;
        }
        set
        {
            _email.Email = value;
            _email.UpdateDate = DateTime.Now();
        }
    }

    public virtual Kiosk Kiosk {get;set;}

    public virtual bool HasKiosk
    {
        get
        {
            return (Kiosk != null);
        }
    }
}

public class Kiosk
{
    public virtual string XmlKiosk {get;set;}
}

public class Email
{
    public virtual string Email {get;set;}
    public virtual DateTime UpdateDate {get;set;}
}

有什么想法吗?

非常感谢, 阿米尔。

1 个答案:

答案 0 :(得分:0)

使用this article 我通过“Kiosk”和“电子邮件”课程中的微小修改实现了我想要的目标......

结果如下:

public class Kiosk
{
    private int UserId {get;set;}
    private User User {get;set;}

    protected Kiosk();

    public Kiosk(User user)
    {
        User = user;
    }

    public virtual string XmlKiosk {get;set;}
}

public class Email
{
    private int UserId {get;set;}
    private User User {get;set;}

    protected Email();

    public Email(User user)
    {
        User = user;
    }   

    public virtual string Email {get;set;}
    public virtual DateTime UpdateDate {get;set;}
}

映射看起来像这样:

    Public class UserMapping : IAutoMappingOverride<User>
    {
        public void override Map(AutoMapping<User> mapping)
        {
            mapping.Id(o => o.Id) // Not needed, already mapped with auto mapper, just for the example...

            mapping.HasOne(o => o.Kiosk)
                .Cascade.All();
            mapping.HasOne(Reveal.Member<User, Email>("_email"))
                .Cascade.All();

            mapping.IgnoreProperty(o => o.HasKiosk); // Simple getter, no mapping needed here.
        }
    }

    public class KioskMapping : IAutoMappingOverride<Kiosk>
    {
        public void override Map(AutoMapping<Kiosk> mapping)
        {
            mapping.Id(Reveal.Member<Kiosk>("UserId"), "ColumnName");

            mapping.HasOne<User>(Reveal.Member<Kiosk, User>("User")
                .Constrained()
                .ForeignKey();
        }
    }

    public class EmailMapping : IAutoMappingOverride<Email>
    {
        public void override Map(AutoMapping<Email> mapping)
        {
            mapping.Id(Reveal.Member<Email>("UserId"), "ColumnName");

            mapping.HasOne<User>(Reveal.Member<Email, User>("User")
                .Constrained()
                .ForeignKey();
        }
    }       

像魅力一样,谢谢大家。