如何在实体框架6中连接两个实体以获得翻译文本



我使用的是EF 6 Code First,我希望我的客户能够用多种语言引入新记录。为了存储它,我用一个自定义键将所有文本保存在Dictionary实体中,并通过这个键从我的另一个实体引用它。

这是我的实体的基本样本:

Dictionary
ID  Key          IsoCode    Value
1   firstEntry   en-US      My new entry
2   secondEntry  en-US      My second entry
3   firstEntry   es-ES      Mi nueva entrada
Entries    
ID   Name         CreationDate
1    firstEntry   2020-11-04
2    secondEntry  2020-11-07

我想要实现的是用ISO代码查询Entries实体,并获得一个新的实体,其中Name字段被Dictionary实体中的Value字段替换。

这就是我现在拥有的:

public List<Entry> GetEntries(string isoCode)
{    
var query = (from e in dbContext.Entry
join d in dbContext.Dictionary on e.Name equals d.Key
where d.IsoCode == isoCode
select new
{
entry= e,
Text = d.Value
}).ToList();
return query.Select(t => new Entry
{
Id = t.entry.Id,
Name = t.Text,
CreationDate = t.CreationDate
}).ToList();
}

有没有更好的方法可以在不创建两个列表的情况下做到这一点?这种使用密钥获取翻译文本的方法是最佳实践吗?还是我没有抓住要点?

这里有一个使用2个列表而不是表的代码的工作示例(当然(。

您可以简单地在第一个查询中创建条目。在该例程中不需要.ToList()。只需返回IEnumerable

using System;
using System.Collections.Generic;
using System.Linq;
namespace JoinEntities
{
class Program
{
static List<Dict> dictionary = new List<Dict>
{
new Dict
{
ID = 1,
Key = "firstEntry",
IsoCode = "en-US",
Value = "My new entry"
},
new Dict
{
ID = 2,
Key = "secondEntry",
IsoCode = "en-US",
Value = "My second entry"
},
new Dict
{
ID = 3,
Key = "firstEntry",
IsoCode = "es-ES",
Value = "Mi nueva entrada"
},
};
static List<Entry> entries = new List<Entry>
{
new Entry
{
Id = 1,
Name = "firstEntry",
CreationDate = new DateTime(2020, 11, 04)
},
new Entry
{
Id = 1,
Name = "secondEntry",
CreationDate = new DateTime(2020, 11, 07)
}
};

static void Main(string[] args)
{
var list = GetEntries("en-US");
}
public static IEnumerable<Entry> GetEntries(string isoCode)
{
return from e in entries
join d in dictionary on e.Name equals d.Key
where d.IsoCode == isoCode
select new Entry
{
Id = e.Id,
Name = d.Value,
CreationDate = e.CreationDate
};
}
}
internal class Dict
{
public int ID { get; set; }
public string Key { get; set; }
public string IsoCode { get; set; }
public string Value { get; set; }
}
internal class Entry
{
public object Id { get; set; }
public object Name { get; set; }
public object CreationDate { get; set; }
}
}

最新更新