实体框架林克到对象映射
本文关键字:对象 映射 林克 框架 实体 | 更新日期: 2024-11-05 00:59:27
我有一个问题。
数据库舍马
==================
|parts |
==================
| partId |textId |
==================
========================
texts |
========================
|TextId|LanguageId|text|
========================
============================
languages |
============================
|LanguageId|LanguageIsoCode|
============================
我想将此结果映射到以下对象
public long PartId { get; set; }
public Dictionary<string,string> Name { get; set; }
例如。
{
PartId: 32020
Name: {["en": "Blah", "es": "Blah2"]}
}
这是我尝试过的,但我在这个查询中遇到了超时。
var query = (from p in _context.epc_parts
select new //select first dynamic object
{
PartId = p.PartID,
Code = p.PartName,
Name = (from trans in _context.epc_texts
join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID
where p.TextID == trans.TextID
select new
{
LanguageId = lang.shortname.ToLower(),
Caption = trans.Caption
})
}).AsEnumerable().Select(x => new SearchPartModel //transform it here when we can use dictionary
{
Code = x.Code,
PartId = x.PartId,
Name = x.Name.ToDictionary(t => t.LanguageId, t => t.Caption)
});
零件表大约有 60k 行,每行有 7 个翻译。无法使用导航属性,因为 Shema 不使用外键,并且模型是从 db 生成的。
我已经用这个查询解决了它。对于整个查询,大约需要 20 秒才能加载所有可以用于此目的的内容。我首先使用组。
(from p in _context.epc_parts
join trans in _context.epc_texts on p.TextID equals trans.TextID
join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID
select new
{
PartId = p.PartID,
Code = p.PartName,
Caption = trans.Caption,
LanguageId = lang.shortname.ToLower()
}).AsEnumerable().GroupBy(x => x.PartId).Select(g => new SearchPartModel
{
Code = g.Select(x => x.Code).FirstOrDefault(),
PartId = g.Key,
Name = g.Select(x => new
{
x.LanguageId,
x.Caption
}).Distinct().ToDictionary(y => y.LanguageId, y => y.Caption)
});
from p in _context.epc_parts
join trans in _context.epc_texts on p.TextID equals trans.TextID
join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID
select new {
PartId = p.PartID,
Code = p.PartName,
Name = new
{
LanguageId = lang.shortname.ToLower(),
Caption = trans.Caption
}
}
这应该更好,否则在查询texts
表的每个part
的当前实现中