我有兩個表:表1:角色表和表2:特權表。使用LINQ獲取基於字符串中多個字段的字段使用LINQ
在RolesTable樣本數據
Name |Description |ModulePrivIds|FunctionPrivIds|Active
=================================================================
Role1|This is a Test Role |1,2 |3,4 |1
Role2|This is another Role |2,3 |1,3 |0
注:ModulePrivId和FunctionPrivIds對應IDS在PrivilegeTable
樣本數據中PrivilegeTable
ID | Name |Description
========================
1 |Priv1 |This is Priv1
2 |Priv2 |This is Priv2
3 |Priv3 |This is Priv3
4 |Priv4 |This is Priv4
現在我想在所有角色的網格中顯示數據。因此,我想使用特權表來顯示特權名稱,而不是ModulePrivId和FunctionPrivIds。
這是我正在嘗試,但無法達到預期的效果。
var answer = (from r in database.RolesRepository.Get()
join p in database.PrivilegesRepository.Get()
on r.ModulePrivilegeIds equals p.Id.ToString() into ModuleWisePrivileges
from p1 in ModuleWisePrivileges.DefaultIfEmpty()
from r1 in database.RolesRepository.Get()
join p01 in database.PrivilegesRepository.Get()
on r1.FunctionPrivilegeIds equals p01.Id.ToString() into FunctionWisePrivileges
from p2 in FunctionWisePrivileges.DefaultIfEmpty()
select new
{
Name = r.Name,
Description = r.Description,
ModuleWisePrivileges = ModuleWisePrivileges,
FunctionWisePrivileges = FunctionWisePrivileges,
Active = r.Active
}).ToArray();
return answer;
我也試過以下,但沒有成功。
var answer = (from r in database.RolesRepository.Get()
join p in database.PrivilegesRepository.Get()
on p.Id.ToList().Where(p => Id.Contains(r.ModulePrivilegeIds.ToString()) into ModuleWisePrivileges)
from p1 in ModuleWisePrivileges.DefaultIfEmpty()
from r1 in database.RolesRepository.Get()
join p01 in database.PrivilegesRepository.Get()
on r1.FunctionPrivilegeIds equals p01.Id.ToString() into FunctionWisePrivileges
from p2 in FunctionWisePrivileges.DefaultIfEmpty()
select new
{
Name = r.Name,
Description = r.Description,
ModuleWisePrivileges = ModuleWisePrivileges,
FunctionWisePrivileges = FunctionWisePrivileges,
Active = r.Active
}).ToArray();
爲什麼不簡單地使用'特權'和'角色'之間的'm:n'關係?我認爲這是不可能的,沒有某種黑客攻擊(即:sql視圖會讓它成爲'm:n' ...然後你遇到插入問題)或者將整個表格加載到你的應用程序並且在本地處理它(那就是你在代碼中試圖做什麼,這有點緩慢和頭痛)... –
你知道這是一個不好的數據庫佈局?良好的數據庫佈局將使用RolesTable和PrivilegesTable之間的映射表。這樣,你可以使用標準的導航屬性。 –
@DanielHilgarth:我建議他們改變數據庫佈局,但他們似乎不想更改數據庫。你周圍的任何工作都可以建議? –