【问题标题】:Fluent Hibernate One-To-One mapping issueFluent Hibernate 一对一映射问题
【发布时间】:2014-10-08 10:09:01
【问题描述】:

我不确定如何在给定实体下方进行映射。

下面是表格。

Employee { ID, Name, Role_ID } (Role_ID is foreign key from Role table)
Role     {Role_ID, Name }    

以下是类:

class Employee
{
     public virtual string ID { get; set; }
     public virtual string Name { get; set; }
     public virtual Role EmpRole { get; set; }
}

class Role
{
     public virtual string RoleID { get; set; }
     public virtual string Name { get; set; }
}

以下是映射:

  public class EmployeeMap : ClassMap<Employee>
  {
    public EmployeeMap()
    {
        Table("Employee");
        Id(x => x.ID, "ID");
        Map(x => x.Name, "NAME");
        //for relationship not sure which mapping to be used???  

    }
  }

  public class RoleMap : ClassMap<Role>
  {
    public RoleMap()
    {
        Table("Role");
        Id(x => x.RoleID, "ROLE_ID");
        Map(x => x.RoleID, "ROLE_ID");
        Map(x => x.Name, "ROLE_NAME");
        //For relationship not sure what to be used???? 
    }
  }

场景:一名员工将担任一个角色。一个角色可以分配给多个员工。

请建议我如何编写两个实体的关系?

【问题讨论】:

    标签: c#-4.0 nhibernate fluent-nhibernate fluent


    【解决方案1】:

    您正面临最常见的情况。在这种情况下,映射将是 many-to-one,流畅地表示为 .References()

    public EmployeeMap()
    {
        Table("Employee");
        Id(x => x.ID, "ID");
        Map(x => x.Name, "NAME");
        References(x => x.EmpRole , "Role_ID");
    }
    

    最好的概述(我知道)在这里:

    Mapping-by-Code - ManyToOne 亚当巴

    令人惊讶的是,这篇文章不是关于流畅的 NHibernate,而是关于代码映射。然而,后半部分与流利相比 - 并提供了非常全面的概述。小sn-p:

    References(x => x.PropertyName, "column_name")
        .Class<ClassName>()
        .Cascade.SaveUpdate()
        .Fetch.Join()
        .Update()
        .Insert()
        .ReadOnly()
        .Access.Field()
        .Unique()
        .OptimisticLock()
        .LazyLoad(Laziness.Proxy)
        .PropertyRef(x => x.PropertyRef)
        .NotFound.Ignore()
        .ForeignKey("column_fk")
        .Formula("arbitrary SQL expression")
        .Index("column_idx")
        .Not.Nullable()
        .UniqueKey("column_uniq");
    

    如果您要搜索 NHibernate 文档(流畅的操作在它之上),您应该检查:

    5.1.10. many-to-one

    如果你想要 Fluent-NHibernate 文档:

    最后,如果您想查看哪些员工属于每个角色,您可以扩展您的 POCO:

    class Role
    {
         public virtual string RoleID { get; set; }
         public virtual string Name { get; set; }
         public virtual IList<Employee> Employees { get; set; }
    }
    

    并将其映射为&lt;bag&gt;

    HasMany(x => x.Employees)
       .KeyColumn("Role_ID")
       .Inverse()
       .BatchSize(25)
    

    见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-17
      • 2018-05-03
      • 2021-08-22
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多