实体框架父\子检索

时间:2015-02-10 15:07:02

标签: entity

我有一个"组件"的ID父记录,我需要检索所有"附件"儿童记录。我正在使用的网格需要返回一个放置在" TheComponentAttachmentsJoinedTable"我只能检索一条记录。我使用了FirstorDefault的值。这是它接受代码行而不抱怨IEnumerable为int的唯一方法。有人可以解释一下是不正确的吗?

public class Component
{
    public int ID { get; set; }
    public string ComponentCode { get; set; }
    public string ComponentDescription { get; set; }
    public double ComponentWeight { get; set; }
    public double ComponentQuantity { get; set; }
    public string LastModUser { get; set; }
    public DateTime LastModDate { get; set; }

    public virtual ICollection<Attachment> Attachments { get; set; }
    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Element> Elements { get; set; }
}

public class Attachment
{

    public int ID { get; set; }
    public string AttachmentDescription { get; set; }
    public string OriginalName { get; set; }
    public string MimeType { get; set; }
    public byte[] bytes { get; set; }
    public string LastModUser { get; set; }
    public DateTime LastModDate { get; set; }

    //Navigation
    public virtual ICollection<Element> Elements { get; set; }
    public virtual ICollection<Component> Components { get; set; }  //lt M-m
}


public class TheComponentAttachmentsJoinedTable
{
    public int ComponentID { get; set; }
    public int AttachmentID { get; set; }
    public string OriginalName { get; set; }
}

public static List<TheComponentAttachmentsJoinedTable>   ComponentAttachments_GetAllByComponentID(int ComponentID)
    {
        using (TheContext TheDB = new TheContext())
        {
           var r = (from x in TheDB.Component
        .Where(x => x.ID == ComponentID)
        .Include(x => x.Attachments)
                     select new TheComponentAttachmentsJoinedTable
                    {
                        ComponentID = x.ID,
                        AttachmentID = x.Attachments.Select(y => (y.ID)).FirstOrDefault(),
                        OriginalName = x.Attachments.Select(y => y.OriginalName).FirstOrDefault().ToString(),
                    }
     );
return r.ToList();
}

0 个答案:

没有答案