How to get the data from a table in database

Topics: Troubleshooting
Oct 18, 2012 at 2:26 PM

Hi, I would like, within my Controller class, to know how can I retrieve the data from a table in database based on some criteria. Is it through IContentManager or IRepository<UserSubmissionPart> and if you could provide an example will be very useful.

For example the corresponding sql would be:

SELECT id FROM UserSubmissionPart WHERE email = 'test@test.com'

 

Thanks in advance.

Coordinator
Oct 18, 2012 at 5:50 PM

If it's just from one table, then yes, use IRepository and Linq queries on its Table property. Avoid direct SQL as that can easily break DB portability (but it can be done by getting the nHibernate session object, and example of which can be seen in the OrchardPo module).

Oct 19, 2012 at 1:18 PM

When I try to execute the below Test method inside the controller I am getting an exception when for linq {"Object reference not set to an instance of an object."}

public class UserSubmissionPart : ContentPart<UserSubmissionPartRecord> {

   
public string SubmittedBy {
        get
{ return Record.SubmittedBy; }
       
set { Record.SubmittedBy = value; }
   
}

   
public string SubmittedByEmail {
        get
{ return Record.SubmittedByEmail; }
       
set { Record.SubmittedByEmail = value; }
   
}      
}

 
public class UserSubmissionPart : ContentPart<UserSubmissionPartRecord> {

       
public string SubmittedBy {
            get
{ return Record.SubmittedBy; }
           
set { Record.SubmittedBy = value; }
       
}

       
public string SubmittedByEmail {
            get
{ return Record.SubmittedByEmail; }
           
set { Record.SubmittedByEmail = value; }
       
}      
   
}

 
public class UserSubmissionController : Controller {
        private readonly IRepository
<UserSubmissionPart> _repository;      

        private void Test
(string value) {                
            var query
= from s in _repository.Table.ToList()
                       
where s.SubmittedByEmail == value
                       
select s;                
       
}
}
Oct 19, 2012 at 1:34 PM

Your _repository reference never gets assigned an instance. Add constructor to your controller so that autofac can inject the IRepository instance.

public UserSubmissionController(IRepository<UserSubmissionPartRecord> repository)
{
  _repository = repository;
}

Oct 19, 2012 at 1:51 PM

Thank you its working fine now :)