2

我正在尝试将多对多表结构映射到字典,其中键在一个表中,值在另一个表中。

table Rows [Row_ID]

table Columns [Column_ID, Column_Name]

table Cells [Cell_ID, Row_ID, Column_Id, Cell_Value]

public class Row {
    public Row() {
        this.Cells = new Dictionary<string, Cell>();
    }

    public virtual long Id { get; protected set; }

    public virtual IDictionary<string, Cell> Cells { get; set; }
}

public class RowMap : ClassMap<Row> {
    public RowMap() {
        Table("Rows");
        Id(m => m.Id, "Row_Id").GeneratedBy.Identity();
        HasManyToMany<Column>(m => m.Cells).Table("Cells")
            .ParentKeyColumn("Row_Id").ChildKeyColumn("Column_Id")
            .AsMap<string>("Column_Name").Inverse().Cascade.All();
    }
}

public class Column {
    public virtual long Id { get; protected set; }

    public virtual string Name { get; set; }
}

public class ColumnMap : ClassMap<Column> {
    public ColumnMap() {
        Table("Columns");
        Id(m => m.Id, "Column_Id").GeneratedBy.Identity();
        Map(m => m.Name, "Column_Name").Not.Nullable();
    }
}

public class Cell {
    public virtual long Id { get; protected set; }

    public virtual string Value { get; set; }

    public virtual Column Column { get; set; }

    public virtual Row Row { get; set; }
}

public class CellMap : ClassMap<Cell> {
    public CellMap() {
        Id(m => m.Id, "Cell_Id").GeneratedBy.Identity();
        Map(m => m.Value, "Cell_Value").Not.Nullable();
        References(m => m.Column, "Column_Id");
        References(m => m.Row, "Row_Id");
    }
}

一切都正确编译,但是当我尝试访问 Cells 集合时,出现以下错误:

could not initialize a collection: [Sandbox.Row.Cells#1][SQL: SELECT cells0_.Row_Id as
Row1_1_, cells0_.Column_Id as Column2_1_, cells0_.Column_Name as Column3_1_,
column1_.Column_Id as Column1_8_0_, column1_.Column_Name as Column2_8_0_ FROM Cells
cells0_ left outer join Columns column1_ on cells0_.Column_Id=column1_.Column_Id WHERE
cells0_.Row_Id=?]

查看错误消息后,我看到查询正在尝试将键“Column_Name”作为 Cells 表中的字段而不是 Columns 表来访问。

关于如何告诉 NHibernate 将其映射到正确的表的任何想法,或者我试图做的事情是不可能的?

4

1 回答 1

1

在hasmanytomany(中间表:Cells,EntityTable of Cells:Cells)中从未提到过columns表,因此根本无法引用它。我目前看到的唯一选择是更改字典开始。

public virtual IDictionary<Column, Cell> Cells { get; private set; }

HasMany(m => m.Cells)
    .Table("Cells")
    .KeyColumn("Row_Id")
    .AsEntityMap("Column_id")
    .Inverse().Cascade.All();

您可以保存从 column.Name 到列实例的全局字典,以保存往返或将列名非规范化到单元格表中。

于 2012-07-09T05:55:14.593 回答