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);
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.
- , , ? .