【问题标题】:nPoco V3 - many to many not workingnPoco V3 - 多对多不工作
【发布时间】:2016-11-01 11:14:05
【问题描述】:

我有多个角色的用户

public class User 
{
   public int Id {get;set;}
   public string Name {get;set;}
   public List<Role> Roles {get;set;}
}

public class Roles 
{
   public int Id {get;set;}
   public string Key{get;set;}
}

public class UserRoles 
{
   public int UserId {get;set;}
   public int RoleId {get;set;}
}

我试图实现的是在一个查询中获得一个具有所有角色的用户,但到目前为止我失败了。 对于映射,我使用自定义的基于约定的映射器(我可以提供代码,但它相当大)

我尝试了 FetchOneToMany,并按照此处所述尝试了 Fetch

https://github.com/schotime/NPoco/wiki/One-to-Many-Query-Helpers https://github.com/schotime/NPoco/wiki/Version-3

但角色总是空的。 角色和用户本身已正确映射,我确实尝试指定关系,如

For<User>().Columns(x =>
        {
            x.Many(c => c.Roles);
            x.Column(c => c.Roles).ComplexMapping();
        }, true);  

同样没有帮助,角色是空的。

我不知道我错过了什么。 有什么想法吗?

【问题讨论】:

    标签: many-to-many mapping one-to-many npoco


    【解决方案1】:

    ComplexMapping 和关系映射(1-to-n, n-to-n) 是两个不同的东西。

    ComplexMapping 用于为数据映射嵌套对象,这些数据通常位于存在一对一关系的同一个表中。对于这样的事情:

    public class Client 
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
    
        public Client()
        {
            Address = new Address();
        }
    }
    
    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Telephone { get; set; }
        public string Country{ get; set; }
    }
    

    如果您使用的是基于约定的映射器,您的覆盖将如下所示:

     For<Client>().Columns(x =>
     {
         x.Column(y => y.Address).ComplexMapping();
     });
    

    使用基于约定的映射器时需要注意的一点;您必须使用以下代码在扫描仪中启用 ComplexMapping:

    scanner.Columns.ComplexPropertiesWhere(y => ColumnInfo.FromMemberInfo(y).ComplexMapping);
    

    否则,您的覆盖中的 ComplexMapping() 调用将被忽略。

    一对多映射将像这样工作(请参阅NPoco on Github 了解更多信息):

    For<One>()
        .TableName("Ones")
        .PrimaryKey(x => x.OneId)
        .Columns(x =>
        {
            x.Column(y => y.OneId);
            x.Column(y => y.Name);
            x.Many(y => y.Items).WithName("OneId").Reference(y => y.OneId);
        }, true);
    
    For<Many>()
        .TableName("Manys")
        .PrimaryKey(x => x.ManyId)
        .Columns(x =>
        {
            x.Column(y => y.ManyId);
            x.Column(y => y.Value);
            x.Column(y => y.Currency);
            x.Column(y => y.OneId);
            x.Column(y => y.One).WithName("OneId").Reference(y => y.OneId, ReferenceType.OneToOne);
        }, true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 2023-03-22
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 2021-10-26
      • 2011-05-01
      • 2016-08-22
      相关资源
      最近更新 更多