【问题标题】:fluent nhibernate mapping many to many configuration error流利的nhibernate映射多对多配置错误
【发布时间】:2013-06-12 06:35:15
【问题描述】:

我在流畅的 nhibernate 世界中使用 HasManyToMany 方法。这是我的“数据库”应用程序。在这个数据库中,我有一些测试数据。现在我想通过 Query 方法询问数据库,哪个用户可以为应用程序使用什么。

这是我的模型类:

    public class Application
    {
        public virtual int Id { get; protected set; }

        public virtual string Name { get; set; }

        public virtual IList<User> User { get; set; }

        public Application()
        {
            User = new List<User>();
        }
    }

    public class User
    {
        public virtual int Id { get; protected set; }

        public virtual string Name { get; set; }

        public virtual IList<Application> Application { get; set; }

        public User()
        {
            Application = new List<Application>();
        }
    }

这里是映射代码:

    public class ApplicationMap : ClassMap<Application>
    {
        public ApplicationMap()
        {
            Id(x => x.Id);
            Map(x => x.Name);
            HasManyToMany(x => x.User)
               .Table("Access")
               .ParentKeyColumn("user_fk")
               .ChildKeyColumn("id")
               .Cascade.All();
        }
    }

    public class UserMap : ClassMap<User>
    {
        public UserMap()
        {
            Id(x => x.Id);
            Map(x => x.Name);
            HasManyToMany(x => x.Application)
               .Table("Access")
               .ParentKeyColumn("application_fk")
               .ChildKeyColumn("id")
               .Cascade.All();
        }
    }

这是我的数据访问方法:

    public static List<Application> SelectApplicationByUser(int userId)
    {
        var session = SessionManager.CurrentSession;
        return session.Query<Application>().Where(x => x.User.Any(y => y.Id == userId)).ToList();  
    }

现在我收到错误未知列用户 ID。有人可以给我一些刺激吗,我已经搜索了这么久并使用了很多方法,但没有任何效果。我的映射定义有什么问题?或者也许我的 Linq 语句也是错误的。 谢谢

【问题讨论】:

标签: c# nhibernate fluent-nhibernate fluent-nhibernate-mapping


【解决方案1】:

父列是搜索持有人 ID(应用程序)的位置。 child 是要在 user 表中搜索的参考 id 的位置。

public ApplicationMap()
{
   Id(x => x.Id);
   Map(x => x.Name);
   HasManyToMany(x => x.User)
       .Table("Access")
       .ParentKeyColumn("application_fk")
       .ChildKeyColumn("user_fk")
       .Cascade.All();
}

和用户类似

    public UserMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        HasManyToMany(x => x.Application)
           .Table("Access")
           .ParentKeyColumn("user_fk")
           .ChildKeyColumn("application_fk")
           .Inverse()            // this is essential
           .Cascade.All();
    }

注意:集合之一必须映射为Inverse()。这将正确解决插入、更新顺序的问题...

注意2:非常重要的注意事项。 Cascade all 很可能不需要。 在多对多关系中,总是处理对表。这 在这种情况下,级联意味着确实更改所有引用的用户实体, 更改应用程序时。

在这里阅读更多:23.2. Author/Work

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多