我的带有Identity的.NET WebAPI项目提供了几个(注册的)用户可以使用的服务。对服务的访问是按用户授予的,因此UserA可以使用Service1、Service2和Service3,而UserB可以使用Service1、Service2、Service4和Service5。
每个服务都有0..n个设置/配置。服务中使用的设置值也取决于用户。
示例:
我们有用户Alice,Bob,Eve (目前默认的ASP NET身份用户)和服务“随机数”,“搜索”和“天气预报”。随机数不需要设置,搜索需要使用搜索引擎,天气预报需要温度样式(摄氏度/华氏度)和预报提供商。
爱丽丝可以使用所有这三种服务,谷歌作为搜索引擎,weather.com提供摄氏度的天气预报。Bob只能使用以Bing为后端的搜索服务。Eve可以使用Google搜索和accuweather的华氏天气预报。
我被卡在EF的代码优先方法中设计表。任何帮助都是非常感谢的。
发布于 2014-11-20 17:17:51
public class Service
{
[Key]
public int Id {get;set;}
public string Name {get;set;}
}
public class UserService
{
[Key, Column(0)] // this creates a composite key
public int ServiceId {get;set;}
[Key, Column(1)] // this creates a composite key
public string UserId {get;set;}
}因此,这在用户和您提供的服务之间创建了多对多关系。因此,您可以将一个用户添加到多个服务。以下是设置:
public class Settings
{
[Key]
public int Id {get;set;}
public int UserId {get;set;} // the user
public int ServiceId {get;set;} // the service
}因此,要澄清的是,这是基于每个用户每个服务的1个设置。如果您希望每个用户每个服务有多个设置,则必须将其设置为多对多。
希望这将是一个良好的开端。
需要注意的是,我没有使用关系,也就是public virtual Settings Settings {get;set;}。我只是从数据库中加入它,如下所示。我特别不喜欢多对多映射的用户关系,这太神奇了!see one of my answers on SO。我建议你永远不要在EF的多对多关系中使用延迟加载虚拟属性。
为了获得这些服务,我会这样做:
using (var context = new DbContext())
{
var usersWithServices = context.Users.GroupJoin(
context.UserServices,
u => u.Id,
j => j.UserId,
(user, @join) => new {
user,
@join
}).Select(a =>
a.join.GroupJoin(
context.Services,
j => j.ServiceId,
s => s.Id,
(@join, service) => new {
a.user,
@join,
service
})).ToList();
}把这段代码放到LinqPad中,它会跑得像个美人儿,不过它是个野兽。它基本上返回IEnumerable<IEnumerable<>>,在最里面的IEnumerable是一个无值对象,其中包含一个User,UserService,Service。或者至少在Linqpad上,这是我能看出来的。把它放到VS中,你就会确切地知道你在处理什么。
https://stackoverflow.com/questions/27035430
复制相似问题