使用代码优先迁移来生成数据库。
我有这样的亲子关系,每个人都有孩子,孩子可能有自己的孩子等。
public class Person
{
public string Name { get; set; }
public bool Flagged { get; set; }
public virtual ICollection<Person> Children { get; set; }
public virtual Person Master { get; set; }
...
}
找到这些东西的最有效方法是什么?到目前为止,我一直在使用递归查询,这似乎很慢,并不是一件好事。我读到了公用表格表达式,但我不确定这是否符合我的需求并支持EF 代码首次迁移。
答案 0 :(得分:1)
AFAIK实体框架不支持公用表表达式。您应该继续使用数据库视图。对我来说,让父母和孩子的问题看起来像这样。
WITH Children AS
(
SELECT a.*
FROM dbo.Persons a
WHERE Id = 14
UNION ALL
SELECT a.*
FROM dbo.Persons a JOIN Children c ON a.IdParentPerson = c.id
)
SELECT *
FROM Children
/*WHERE Children.Flagged = true*/ /*IF REQUIRED*/
和
WITH Parents AS
(
SELECT a.*
FROM dbo.Persons a
WHERE Id = 16
UNION ALL
SELECT a.*
FROM dbo.Persons a JOIN Parents c ON a.Id = c.IdParentPerson
)
SELECT *
FROM Parents
WHERE Parents.Flagged = true
然后在像
这样的DbSet上使用它var id = YOUR_ID;
using(var context = new Context())
{
var query = context.Set<GroupEntity>().SqlQuery(
" WITH Parents AS " +
" ( " +
" SELECT a.* " +
" FROM dbo.Persons a " +
" WHERE Id = @Id " +
" UNION ALL " +
" SELECT a.* " +
" FROM dbo.Persons a JOIN Parents c ON a.Id = c.IdParentPerson " +
" ) " +
" SELECT * " +
" FROM Parents " +
" WHERE Parents.Flagged = true "
, new SqlParameter("@Id", id));
}