我想知道有没有办法在没有创建视图的情况下连接两个非主键列的表?我有一个名为'Make'的表,其中包含'Name'和'Year'列,我希望与另一个名为'Style'的表连接,其中包含'MakeName'和'MakeYear'列。一个'Make'可以有很多'Style'。 以下是我到目前为止创建的实体:
public class Make
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Year { get; set; }
public virtual IList<Style> Styles { get; set; }
}
public class Style
{
public virtual int Id { get; set; }
public virtual string MakeName { get; set; }
public virtual string MakeYear { get; set; }
public virtual string Class { get; set; }
public virtual Make Make { get; set; }
}
这些是我到目前为止的班级地图:
public class MakeMap : ClassMap<Make>
{
public MakeMap()
{
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.Year);
// Bad mapping...
//HasManyToMany(x => x.Styles).Table("Make").AsBag()
.ParentKeyColumn("MakeName")
.ChildKeyColumn("MakeYear").Cascade.All();
Table("Make");
}
}
public class StyleMap : ClassMap<Style>
{
public StyleMap()
{
Id(x => x.Id);
Map(x => x.Class);
Map(x => x.MakeName);
Map(x => x.MakeYear);
// Ends up overwriting the "MakeName" column
References(x => x.Make).Column("MakeName").PropertyRef("Name").
Column("MakeYear").PropertyRef("Year");
Table("Style");
}
}
谢谢!
答案 0 :(得分:4)
3个选项,我会优先考虑第一个
选项:
将db schema
更改为包含make id
而不是名称和年份到样式表中
选
References(x => x.Make)
.Formula("(Select s.Id FROM Style s WHERE s.Name = MakeName AND s.Year = MakeYear)");
public class Make
{
public virtual int Id { get; set; }
public virtual MakeId BusinessId { get; private set; }
}
public class MakeId
{
public virtual string Name { get; set; }
public virtual string Year { get; set; }
}
public class MakeMap : ClassMap<Make>
{
public MakeMap()
{
Id(x => x.Id);
Component("BusinessId", c =>
c.Map(x => x.Name);
c.Map(x => x.Year);
});
HasMany(x => x.Styles)
.PropertyRef("BusinessId")
.KeyColumns.Add("MakeName", "MakeYear")
.Cascade.All();
Table("Make");
}
}
public class StyleMap : ClassMap<Style>
{
public StyleMap()
{
Table("Style");
Id(x => x.Id);
Map(x => x.Class);
References(x => x.Make)
.PropertyRef("BusinessId")
.Columns.Add("MakeName", "MakeYear");
}
}