nPoco V3 - 许多人都没有工作

时间:2016-11-01 11:14:05

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

我的用户有很多角色

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);  

再一次,它没有帮助,角色是空的。

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

1 个答案:

答案 0 :(得分:0)

ComplexMapping和关系映射(1到n,n到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);