开发者

Can ExecuteQuery return a DBML generated class without having it fetch all the information for that class?

开发者 https://www.devze.com 2023-01-06 01:22 出处:网络
I have a couple of DBML generated classes which are linked together by an id, e.g. ClassA { AID, XID, Name

I have a couple of DBML generated classes which are linked together by an id, e.g.

ClassA {
    AID,
    XID,
    Name
}

ClassB {
    AID,
    ExtraInfo,
开发者_JS百科    ExtraInfo2
}

In using something like db.ClassAs.Where(XID == x) and iterating through that result, it ends up executing a query for each of the ClassAs and each of ClassBs, which is slow.

Alternatively, I've tried to use ExecuteQuery to fetch all the info I care about and have that return a ClassA. In iterating over that I end up with it doing the same, i.e. doing alot of individual fetches vs. just 1. If I store it in a ClassC (that is not associated with a DB entity) which has the fields of interest of both ClassA and ClassB, this query is much faster, but it's annoying b/c I just created IMO an unnecessary ClassC.

How can I still use ClassA, which associates to ClassB, and still use ExecuteQuery to run 1 query vs. A*B number of queries?


If you have associations you shouldn't need to use ExecuteQuery().

Here's an example using some imaginary Book Library context and anonymous types for the result:

var results = 
    Books
    .Where(book => book.BookId == 1)
    .Select(book =>
        new
        {
            book.Name,
            AuthorName = book.Author.Name,  //Is a field in an associated table.
            book.Publisher, //Is an associtated table.
        });

EDIT: without anon types

var results = 
        Books
        .Where(book => book.BookId == 1)
        .Select(book =>
            new BookResult()
            {
                BookName = book.Name,
                AuthorName = book.Author.Name,  //Is a field in an associated table.
                Publisher = book.Publisher, //Is an associtated table.
            });
0

精彩评论

暂无评论...
验证码 换一张
取 消