【问题标题】:NHibernate OneToMany Mapping By CodeNHibernate OneToMany 代码映射
【发布时间】:2018-08-17 20:18:46
【问题描述】:

我在互联网上看到了很多关于使用 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,但现在我想在从数据库中获取特定的 VehiculeModel 时填充我的 UserModel。

这里我的模型关系是 OneToOne。 同样出于设计目的,我永远不会查询用户以获取他的车辆列表,因此我的用户模型中不需要“车辆模型列表”。

如果您有任何提示,关于如何在我的 Map 类中映射它(看到很多 xml 映射,但我想通过代码映射它),将不胜感激。

谢谢

【问题讨论】:

  • 感谢您的文档,不幸的是我已经阅读了它们,但它对我没有帮助。我也犯了一个错误,这是一个 OneToOne 关系我更新了我的帖子

标签: c# nhibernate mapping


【解决方案1】:

我终于成功了。 事实上,没什么好复杂的,我只是忘记在 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)
        })
    }
}

也许它可以帮助别人。

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多