1

给定以下(简化的)类:

public class Master
{
    public int Id { get; set; }
    public string UniqueName { get; set; }
    public virtual List<Detail> Details { get; set; }
}

public class Detail
{
    public int Id { get; set; }
    public string UniqueCode { get; set; }
}

如何使用 Linq to Entities 选择一个特定的 Detail 实例,给 Master 一个 UniqueName,Detail 一个 UniqueCode?

请注意,从 Detail 到 Master 没有导航属性。

如果有导航属性,我想我可以这样做:

Detail detail = (from m in ctx.Master.Include(p=>p.Details)
                 join d in ctx.Details
                 on m.Id = d.MasterId
                 where m.UniqueName == "Something" && d.UniqueCode == "Else"
                 select d).SingleOrDefault();

如果没有从 Detail 到 Master 的导航属性,如果不首先获取 Master 包括该 Master 的所有 Detail 实例,然后迭代 Detail 实例,我看不到如何继续。如果给定的 Master 有许多 Detail 实例,那可能会非常低效。

4

2 回答 2

0

尝试

var detail = ctx.Master.Where(m => m.UniqueName == "Something")
    .Select(m => m.Details.Where(d => d.UniqueCode == "Else").FirstOrDefault())
    .SingleOrDefault();
于 2012-09-11T05:40:35.277 回答
0

我不完全确定您使用 linq 到对象或 linq 到实体。如果只涉及您的课程,请尝试以下查询:

    var mst = new List<Master> { 
        new Master { Id = 1, UniqueName = "Something", Details = new List<Detail> { 
            new Detail { Id = 10, UniqueCode = "Else" }, new Detail { Id = 11, UniqueCode = "det1" }} 
        } ,
        new Master { Id = 2, UniqueName = "mast2", Details = new List<Detail> { new Detail { Id = 20, UniqueCode = "det2" } } } 
    };

    var detail = (from d in
                        ((from m in mst
                            where m.UniqueName == "Something"
                            select m.Details).SingleOrDefault())
                where d.UniqueCode == "Else"
                select d).SingleOrDefault();

如果您有数据表,那么 Detail 表可能有一个 MasterID (int) 列,所以我会尝试以下查询:

    var detail = (from d in ctx.Detail
                    where d.MasterID == (
                        (from m in ctx.Master
                         where m.UniqueName == "Something"
                         select m.Id).SingleOrDefault())
                    && d.UniqueCode == "Else"
                    select d).SingleOrDefault();
于 2012-09-13T11:44:51.423 回答