I have a public method called LoadContact() in the Contact class. I want to load the contact data using Linq and assign the values to ‘this’ instance.
So far I have …..
var contact = (from cont in db.Contacts
from note in db.Contacts_Notes.Where(n => n.ContactID == cont.ContactID).DefaultIfEmpty()
where cont.AccountID == this.AccountID && cont.ContactID == this.ContactID
select new Contact
{
AccountID = cont.AccountID,
CompanyName = cont.CompanyName,
ContactID = cont.ContactID,
Firstname = cont.Firstname,
JobTitle = cont.JobTitle,
Lastname = cont.Lastname,
Notes = note.Note
}).SingleOrDefault();
if(contact != null)
{
this.AccountID = contact.AccountID;
this.CompanyName = contact.CompanyName etc etc etc
}
.,.. but this seems really long winded. How can I assign the results directly to the current instance?
Is there a reason why you don’t make it a static method which return a new contact? The way you wants to do it looks like bad design (depending on why you do it).
I would suggest you made it static so it could be used like:
instead of
This way you would be able to just return the contact you found with your query like: