Zero projection of an object in the Entity Framework

I have the following SQL Server 2005 database schema:

CREATE TABLE Messages (
   MessageID int,
   Subject varchar(500),
   Text varchar(max) NULL,
   UserID NULL
)

The "UserID" column, which may be zero, is the foreign key and table links

CREATE TABLE Users (
   UserID int,
   ...
)

Now I have several POCO classes with the names Message, User, etc., which I use in the following query:

public IList<Message> GetMessages(...) {
  var q = (from m in dataContext.Messages.Include("User")
           where ...
           select m); // could call ToList(), but...

  return (from m in q
          select new Message {
            ID = m.MessageID,
            User = new User {
              ID = m.User.UserID,
              FirstName = m.User.FirstName,
              ...
            }
          }).ToList();
}

Now note that I recommend the entity structure β€” using Include (β€œUsers”) β€”load the user associated with the message, if any. Also note that I do not call ToList () after the first LINQ statement. Thus, only the specified columns in the projection list β€” in this case, MessageID, UserID, FirstName β€” will be returned from the database.

: Entity Framework UserID == NULL, , , Int32, DB NULL.

return (from m in q
        select new Message {
           ID = m.MessageID,
           User = m.User == null ? null : new User {
              ID = m.User.UserID,
              ...
           }
        }).ToList()

NotSupportedException , , , , int, string, guid.

- , , ? .

+3
3

"", , UserID . , "int" "int"? (nullable int).

+2

, 1 1.

0

Since you are done .Include("Users"), you can simply cross the property Userin the object Messageto get the information you need.

0
source

Source: https://habr.com/ru/post/1697578/


All Articles