Reputation: 63
Im new to .Net Web API.
I want to get all records where CreatedBy = 1 (This is not a primary key).
My model
public class Subject
{
[Key]
public int Id { get; set; }
public int UniId { get; set; }
public bool IsActive { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
}
My get method in Controller
public Subject Get(int id)
{
IQueryable<Subject> query;
return query = from Subjects in db.SubjectContext.Where(v => v.CreatedBy == id).ToList();
}
Upvotes: 2
Views: 9559
Reputation: 460
public Subject Get(int id)
{
IQueryable<Subject> query;
return query = from Subjects in db.SubjectContext.Where(x => x.CreatedBy == id).Select(s => new Subject()
{
Id = s.Id,
UniId = s.UniId,
IsActive = s.IsActive,
Name s.Name,
Code = s.Code,
CreatedBy = s.CreatedBy,
UpdatedBy = s.UpdatedBy
}).ToList();
}
Upvotes: 0
Reputation: 5258
Main issue is your Get
method in the Controller
is setup to return a single Subject
object, not a List<Subject>
. Your query looks correct.
The main change would need to be as follows
public List<Subject> Get(int id)
{
IQueryable<Subject> query;
return query = from Subjects in db.SubjectContext.Where(v => v.CreatedBy == id).ToList();
}
On a side note, the variable name id
is ambiguous. Using something like createdById
will indicate to the casual observer at first glance the id
variable represents a User who created many Subjects
rather than the id of a Subject
.
And, I'd say the same thing for the method name Get
... Get what? Get is also too close to the C# keyword get
used within property declarations. It should be more descriptive. Just a few quick notes that don't affect your issue :)
Finally I will note the way you are returning from the function is unorthodox, though technically correct and will compile. You can skip the variable assignment in the return statement or even skip using a variable altogether and just return the List<Subject>
.. I also added a using statement for a DataContext which is the best practice:
public List<Subject> Get(int id)
{
using(var context = new YourDataContext())
{
var queryResult = (from Subjects in db.SubjectContext.Where(v => v.CreatedBy == id)).ToList();
return queryResult;
}
}
Or without LINQ statements,
public List<Subject> Get(int id)
{
using(var context = new YourDataContext())
{
return context.Subjects.Where(v => v.CreatedBy == id)).ToList();
}
}
Upvotes: 6