[英]SQLite EntityFramework Many to Many Db First
I have three SQLite tables: 我有三个SQLite表:
**PK = Primary Key, FK = Foreign Key ** PK =主键,FK =外键
I created ADO.NET model and I wanted to get all the Categories from the database. 我创建了ADO.NET模型,并希望从数据库中获取所有类别。 My Category class looks like this: 我的类别类如下所示:
class Category
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Element> Elements{ get; set; }
}
I created function: 我创建了函数:
public List<Category> GetCategories()
{
List<Category> categories;
using (var db = new MyDb())
{
categories= db.Categories.Select(p => new Category
{
Id = p.Id,
Name = p.Name,
Elements = ????
}).ToList();
}
return categories;
}
and I can't get list of Elements that belong to category. 我无法获得属于类别的元素列表。 I can only get list of elements from ElementsCategories table. 我只能从ElementsCategories表中获取元素列表。 How can I set list of Elements to Elements field in Category object? 如何在Category对象的Elements字段中设置Elements列表?
According to what you describe you have mapped the junction table ( ElementsCategories
) as an entity, in that case your query would be like this: 根据您的描述,您已将联结表( ElementsCategories
)映射为一个实体,在这种情况下,查询将如下所示:
public List<Category> GetCategories()
{
List<Category> categories;
using (var db = new MyDb())
{
categories= db.Categories.Select(p => new Category
{
Id = p.Id,
Name = p.Name,
Elements = p.ElementsCategories.Select(ec=>ec.Element)
}).ToList();
}
return categories;
}
Now, this is not going to work if Category
is an entity type. 现在,如果“ Category
是实体类型,则此方法将不起作用。 I'm supposing that Category
class you are showing is a DTO . 我假设您显示的Category
类是DTO 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.