我在互联网上看到了很多关于用 nhibernate 映射关系对象的例子,但我无法制作我的作品。
我有两个模型作为示例:
public class Vehicule
{
public virtual int Id { get; set; }
public virtual int Brand { get; set; }
public virtual int Color { get; set; }
public virtual int UserID { get; set; }
public virtual UserModel User { get; set; }
}
public class VehiculeMap: ClassMapping<Vehicule>
{
public VehiculeMap()
{
Table("G1Vehicule");
Id(x => x.Id, map => { map.Column("id"); });
Property(x => x.Brand, map => { map.Column("brand"); });
Property(x => x.Color, map => { map.Column("color"); });
Property(x => x.UserID, map => { map.Column("user_id"); });
}
}
public class UserModel
{
public virtual int Id { get; set; }
public virtual int Username { get; set; }
}
public class UserModelMap : ClassMapping<UserModel>
{
public UserModelMap()
{
Table("Users");
Id(x => x.Id, map => { map.Column("id"); });
Property(x => x.Username, map => { map.Column("username"); });
}
}
以前,我只显示 UserId,但现在我想在从数据库中获取特定的车辆模型时填充我的 UserModel。
在这里,我的模型关系是一对一的。同样出于设计目的,我永远不会查询用户以获取他的车辆列表,因此我不需要在我的UserModel中具有"车辆模型列表"。
如果您有任何提示,关于我如何在我的 Map 类中映射它(看到很多 xml 映射,但我想通过代码映射它(将不胜感激。
谢谢
我终于让它工作了。事实上没有什么复杂的,我只是忘了在 Nhibernate 的映射类列表中添加我的第二个模型 (UserModelMap(。
public class VehiculeMap: ClassMapping<Vehicule>
{
public VehiculeMap()
{
Table("G1Vehicule");
Id(x => x.Id, map => { map.Column("id"); });
Property(x => x.Brand, map => { map.Column("brand"); });
Property(x => x.Color, map => { map.Column("color"); });
Property(x => x.UserID, map => { map.Column("user_id"); });
ManyToOne(x => x.User, map => {
map.Column("user_id"),
map.Fetch(FetchKind.Join),
map.notFound(NotFoundMode.Ignore)
})
}
}
也许它可以帮助其他人。