ServiceStack OrmLite多对一关系

问题描述 投票:1回答:1

我刚开始使用服务堆栈ORMLite for SQL Server,但无法弄清楚一些事情。让我举例告诉你,我想要实现的目标:

我有2个表 - 用户和角色

public partial class Users : IHasId<int>
{
[AutoIncrement]
public int Id { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[References(typeof(Roles))]
[Required]
public int RolesId { get; set; }
}

public partial class Roles : IHasId<int>
{
[AutoIncrement]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}

用户只能属于1个角色。但是许多用户也可以成为同一个角色的一部分。例:

User 1 - Role 1
User 2 - Role 1
User 3 - Role 2

当我执行此代码时

db.LoadSelect<Users>(x => x.Id == 1);

我得到了Users对象。我希望查询也返回Roles对象(而不是我单独查询Roles表),我该怎么做?我在这里错过了什么?我不想要“有多少用户有X角色?” (典型的一个2很多这样的关系:ServiceStack OrmLite mapping with references not working),而不是我想要“这个用户的角色是什么?”

c# orm servicestack many-to-one ormlite-servicestack
1个回答
3
投票

用户只能属于1角色是OrmLite中使用self references通过向Users表添加Roles属性支持的1:1关系,例如:

public partial class Users : IHasId<int>
{
    [AutoIncrement]
    public int Id { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Password { get; set; }

    [References(typeof(Roles))]
    [Required]
    public int RolesId { get; set; }

    [Reference]
    public Roles Roles { get; set; }
}

public partial class Roles : IHasId<int>
{
    [AutoIncrement]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

然后在使用Load* API时填充,例如:

db.CreateTable<Roles>();
db.CreateTable<Users>();

db.Insert(new Roles { Name = "Role 1" });
db.Insert(new Roles { Name = "Role 2" });

db.Insert(new Users { Email = "[email protected]", Password = "test", RolesId = 1 });
db.Insert(new Users { Email = "[email protected]", Password = "test", RolesId = 1 });
db.Insert(new Users { Email = "[email protected]", Password = "test", RolesId = 2 });

var user1 = db.LoadSelect<Users>(x => x.Id == 1);

user1.PrintDump();

打印出用户1和角色1:

[
    {
        Id: 1,
        Email: [email protected],
        Password: test,
        RolesId: 1,
        Roles: 
        {
            Id: 1,
            Name: Role 1
        }
    }
]

我已经创建了一个你可以试验的Live example of this on Gistlyn

© www.soinside.com 2019 - 2024. All rights reserved.