How to select column in web api using LINQ - linq

I'm really a newbie in ASP.NET, I have a table consists of 4 columns, id, name, address, and phone. I'd like to do a query select id, name from table x but I have no idea how to write it using LINQ in ASP.NET web API
public class rateperjamallController : ApiController
{
public double GET()
{
TeamDataContext db1 = new TeamDataContext();
var item = db1.Teams.Select(c => c);
var id = item.Select(a => a.id);
return id;}
}
}
Does anyone have any idea to help me since I am really a newbie?

Are you looking fora specific record in the dataset? If yes, you need to pass the id or name and create a query for that. For example, this is what you can do: (if you pass id as a parameter)
public class rateperjamallController : ApiController
{
public double GET(string id)
{
TeamDataContext db1 = new TeamDataContext();
return db1.Teams.Where(x => x.id == id)?.First();
}
}

Related

Is there a way I can paginate the included list in a linq query

Hope you're doing well,
I was trying to optimize my reads with entity framework, where I arrived at a position, where I get a record from database by id, and I want to include a one-to-many related list, but I don't want to get all data of the list, just a few, so I want to kind of paginate it.
I want to do this process as long as data is in IQueryable state, I don't want to load all data of list in memory and that paginate it as enumerable.
Let's say the query is like below:
var author = await _dbContext.Authors.Where(x => x.Id == id)
.Include(x => x.Books) // <-- paginate this !!??
.FirstOrDefaultAsync();
Entities represent Data state. Pagination and presentation concerns are View state. Entity Framework can help bridge that gap, but it does so by enabling projection so that you can build View state from Data state. Don't pass entities to views, instead build and pass ViewModels to represent the data in accordance to translations and limitations you want for the view.
For instance if you want to pass Author details with their 5 most recent books:
public class AuthorViewModel
{
public int Id { get; set; }
public string Name { get; set; }
// Any other relevant fields...
public ICollection<BookViewModel> RecentBooks = new List<BookViewModel>();
}
public class BookViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime PublishedDate { get; set; }
// Any other relevant fields...
}
var author = await _dbContext.Authors
.Where(x => x.Id == id)
.Select( x => new AuthorViewModel
{
Id = x.Id,
Name = x.Name,
RecentBooks = x.Books
.OrderByDescending(b => b.PublishedDate)
.Select(b => new BookViewModel
{
Id = b.Id,
Name = b.Name,
PublishedDate = b.PublishedDate
}).Take(5)
.ToList()
}).SingleOrDefault();
This gives you the benefit of structuring the data how you want to present it, while generating efficient queries against the database. You can configure tools like Automapper to perform this kind of mapping to use it's ProjectTo<AuthorViewModel>() as a more succinct alternative.

Realm Xamarin LINQ Object

What is the correct way to query Realm with LINQ where the query includes fields from other Realm objects? For example:
public class Department : RealmObject
{
[Primary Key]
public string UniqueId { get; set; }
}
public class Employee : RealmObject
{
[Primary Key]
public string Name { get; set; }
// Parent
public Department Department { get; set; }
}
Then I would expect to be able to do something like:
var employee = realm.All<Employee>().SingleOrDefault( e => e.Department.UniqueId == fooId && e.Name == fooName );
But this always returns no matches. Where() also returns no matches. However, eliminating the e.Department and searching only on employee name works fine but obviously does not scope to Department as intended.
This is with the latest Realm Xamarin 0.80.
What am I doing wrong?
Querying by nested RealmObjects attributes is not currently supported:
Just to clarify here, we don't yet support queries on related objects like this. We will in the future, but there is no timeline at the moment.
The following is also not currently supported:
var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter & emp.Name == "StackOverflow");
The left-hand side of the And operator must be a direct access to a persisted property in Realm.
Unable to process '(emp.Department == value(Realm080.App+c__AnonStorey1).deptFilter)'.
You can do direct RealmObject equalities, just not in the same Linq expression, so break it down further into a sub-query.
Example of how I currently do it:
var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter);
var employees = employeesByDept.Where((Employee emp) => emp.Name == "StackOverflow");
foreach (var emp in employees)
{
D.WriteLine(emp.Name);
}
Note: https://github.com/realm/realm-dotnet/issues/723

How to delete a single record from a list of records stored in a session

I have the following code
here is how I add a list of values to session
public ActionResult Add(Product product)
{
if (Session["AddToCart"] == null)
{
Session["AddToCart"] = new List<Product>();
}
var list = (List<Product>)Session["AddToCart"];
list.Add(product);
}
but how to remove a single record when a session contains multiple records. I am trying to pass an Id but it is not removing the record from the session. Here is how I perform the next step.
Public ActionResult Remove(Product product)
{
Product prod=db.Products.Single(x=>x.Id==product.Id);
var list=(List<Product>)Session["AddToCart"];
//Is this the correct approach
list.Remove(prod);
}
The above code doesn't works. Am I correct or is there anything missing plz correct the above code. Thanks.
Try this,
var list=(List<Product>)Session["AddToCart"];
list.RemoveAll(p => p.Id == product.Id);
Your choice of finding the product with the code db.Products.Single(x=>x.Id==product.Id); may not be the same object with the one in the session.
Edit:
Or you can implement IEquatable<Product> interface. In this case your code would work too.
public class Product : IEquatable<Product>
{
public int Id;
public bool Equals(Product prod)
{
return prod.Id == Id;
}
// Rest of the class
}

Using Linq Retrieveing the data to SelectListItem

I have class studentList
public class studentList
{
public static IEnumerable<SelectListItem> GetStudents(int? ID)
{
//code is required here
return ;
}
}
Iam getting ID into this method and now, I require all other IDs from the table, excluding the passed parameter ID using linq.
I have Student table which contains Two fieds StudentID and StudentName,
Now I require IDs and Names of the students in the above pattern..
Could any one help me...
Might like to read : SQL to LINQ ( Visual Representation )
var data= form s in Students
where s.StudentID != ID
select new {ID= s.StudenID,Name = s.StudentName};
image presentaion might be like

How can I pass any id to a linq join in [HttpGet] ActionResult for Edit

I am making a web application on MVC3, and I am using linq to communicate with the database.
I made a checkboxlist, where a user can select some options according to their choice and it gets saved in the databse table. The problem is in the Edit part.
The whole scenario is something like this:
The user can register as a restaurant owner or a Motel owner, I have assigned different Business_Type_Id as 1 and 2 for differentiating these two, I have assigned '2' for the Restaurant Business Type, and mapped the cuisines with the perticular business type in the same "Cuisines" table, by adding the "BusinessType" column into the table. the user will be assigned a Business_Id for their Business. I am providing a checkboxlist which generates its options from the database table "Cuisines" where I have given the cuisine list. From the front end the user can choose multiple cuisines according to their chioce what ever they provide in their restaurant. The choices may vary from one restaurant owner to the other, so I am storing the selected values for each and every Restaurant owner in a "BusinessCuisinesMapping" table, where I map the perticular BusinessId with the selected CuisineId by that perticular user.
Now to populate that cuisine list for edit or update I wrote a linq join, but I need to compare it with the Business_Id which is passed to the [HttpGet] ActionResult Edit. And this is point where I got stuck.
This is my linq join code which I am using in the controller:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on new { CuisinesData.Id, id } equals new { BusinessCuisineMappingData.CuisinesId, BusinessCuisineMappingData.BusinessId }
where CuisinesData.BusinessTypeId == 2
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}
This is my DTO class:
public class CusinesDTO
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
I want to comape the "id" with the "BusinessCuisineMappingData.BusinessId" field in my LINQ join, which I am getting through the [HttpGet] Actionresult Edit(int id). It prompts me an error while I try to implement it.
You cannot use a local variable in the join. However, you can use it in a Where clause. So if you do
join ...
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
...
where BusinessCuisineMappingData.BusinessId == id
you'll have the same effect.
"The type of the expressions in join clause is incorrect. Type inference failed in the call to 'Join'"
This suggests the types on either side of your JOIN are not equal. You are getting a compiler error; should be relatively easy to check the types on either side of your JOIN clause.
edit: rereading what you have put, I think something like the below is what you want to do:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
where CuisinesData.BusinessTypeId == id
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}

Resources