我有一种情况,两个表共享相同的密钥,我们只说ID。当我使用FluentMapping映射这两个表时,我如何为我希望ID实际映射到对象的类进行映射。
public class First
{
public virtual int Id {get; set;}
public virtual string Name {get; set; }
}
public class Second
{
public virtual First First {get; set;}
public virtual int Number {get; set; }
}
如何映射第二堂课?第二个表也有一个ID,但它是First表的id的外键。
答案 0 :(得分:1)
class First
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
class Second : First
{
public virtual int Number { get; set; }
}
class FirstMap : ClassMap<First>
{
public FirstMap()
{
Id(f => f.Id).GeneratedBy.HiLo("100");
Map(f => f.Name);
}
}
class SecondMap : SubclassMap<Second>
{
public SecondMap()
{
KeyColumn("Id");
Map(s => s.Number);
}
}
但你的场景也是可能的,但你需要额外的工作,以后在代码中不太好看
class SecondMap : ClassMap<Second>
{
public SecondMap()
{
CompositeId()
.KeyReference(f => f.First, "Id");
Map(s => s.Number);
}
}
class Second
{
public virtual First First {get; set;}
public virtual int Number { get; set; }
// required for Compositekeys
public override bool Equals(object obj)
{
var other = obj as Second;
return (other != null) && (First.Id == other.First.Id) ;
}
// required for Compositekeys
public override int GetHashCode()
{
return First.Id.GetHashCode();
}
}