【问题标题】:ServiceStack OrmLite Many to One RelationshipServiceStack OrmLite 多对一关系
【发布时间】:2017-12-17 04:48:55
【问题描述】:

我刚开始使用 SQL Server 的 Service Stack ORMLite 并无法弄清楚一些事情。让我通过示例向您展示我想要实现的目标:

我有 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】:

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

    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 = "user1@gmail.com", Password = "test", RolesId = 1 });
    db.Insert(new Users { Email = "user2@gmail.com", Password = "test", RolesId = 1 });
    db.Insert(new Users { Email = "user3@gmail.com", Password = "test", RolesId = 2 });
    
    var user1 = db.LoadSelect<Users>(x => x.Id == 1);
    
    user1.PrintDump();
    

    打印出用户 1 和角色 1:

    [
        {
            Id: 1,
            Email: user1@gmail.com,
            Password: test,
            RolesId: 1,
            Roles: 
            {
                Id: 1,
                Name: Role 1
            }
        }
    ]
    

    我创建了一个Live example of this on Gistlyn,你可以尝试一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多