ServiceStack OrmLite多对一关系
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ServiceStack OrmLite多对一关系相关的知识,希望对你有一定的参考价值。
我刚开始使用服务堆栈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),而不是我想要“这个用户的角色是什么?”
答案
用户只能属于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 = "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。
以上是关于ServiceStack OrmLite多对一关系的主要内容,如果未能解决你的问题,请参考以下文章