Problem with get/read Related Data in ASP.NET Core 6.0 - asp.net-core-mvc

I'm trying to visualize the data related countries for the current continent in continent details page.
If we use Razor pages the functional looks like this:
public async Task<IActionResult> OnGetAsync(string id)
{
Continent = await _context.Continents
.Include(c => c.Countries)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.ID == id);
if (Continent == null)
{
return NotFound();
}
return Page();
}
I'm trying to make same request in an ASP.NET Core MVC controller:
public async Task<IActionResult> Details(string id)
{
if (id == null || _context.Continents == null)
{
return NotFound();
}
var continent = await _context.Continents
.Include(x => x.Countries)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.ID == id);
if (continent == null)
{
return NotFound();
}
return View(continent);
}
But the Countries is marked as red:
Error CS1061
'Continent' does not contain a definition for 'Countries' and no accessible extension method 'Countries' accepting a first argument of type 'Continent' could be found (are you missing a using directive or an assembly reference?)
C:\Users\Partsmaster\source\repos\RazorCountry\RazorCountry\Controllers\ContinentsController.cs
How I should modify read related data in the ASP.NET Core MVC controller correctly?
ContinentController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RazorCountry.Data;
using RazorCountry.Models;
using RazorCountry.Models.ViewModels;
namespace RazorCountry.Controllers
{
public class ContinentsController : Controller
{
private readonly AppDbContext _context;
public ContinentsController(AppDbContext context)
{
_context = context;
}
// GET: Continents
public async Task<IActionResult> Index(string searchString, string chosenFilter)
{
var viewModel = new ContinentViewModel();
IQueryable<Continent> continents = _context.Continents;
if (!String.IsNullOrEmpty(searchString))
{
switch (chosenFilter)
{
case "id":
viewModel.Filter = "id";
continents = continents.Where(s => s.ID.Contains(searchString));
break;
case "name":
viewModel.Filter = "name";
continents = continents.Where(s => s.Name.Contains(searchString));
break;
}
}
viewModel.Continents = continents;
viewModel.SearchString = searchString;
return View(viewModel);
}
// GET: Continents/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null || _context.Continents == null)
{
return NotFound();
}
var continent = await _context.Continents.Include(x => x.Countries).AsNoTracking()
.FirstOrDefaultAsync(m => m.ID == id);
if (continent == null)
{
return NotFound();
}
return View(continent);
}
// GET: Continents/Create
public IActionResult Create()
{
return View();
}
// POST: Continents/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Name")] Continent continent)
{
if (ModelState.IsValid)
{
_context.Add(continent);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(continent);
}
// GET: Continents/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null || _context.Continents == null)
{
return NotFound();
}
var continent = await _context.Continents.FindAsync(id);
if (continent == null)
{
return NotFound();
}
return View(continent);
}
// POST: Continents/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("ID,Name")] Continent continent)
{
if (id != continent.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(continent);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ContinentExists(continent.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(continent);
}
// GET: Continents/Delete/5
public async Task<IActionResult> Delete(string id)
{
if (id == null || _context.Continents == null)
{
return NotFound();
}
var continent = await _context.Continents
.FirstOrDefaultAsync(m => m.ID == id);
if (continent == null)
{
return NotFound();
}
return View(continent);
}
// POST: Continents/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
if (_context.Continents == null)
{
return Problem("Entity set 'AppDbContext.Continents' is null.");
}
var continent = await _context.Continents.FindAsync(id);
if (continent != null)
{
_context.Continents.Remove(continent);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ContinentExists(string id)
{
return _context.Continents.Any(e => e.ID == id);
}
}
}
Try to understand "read related data". May be I need to add some ViewModel and rewrite the Details script?
Continent.cs:
using System.ComponentModel.DataAnnotations;
namespace RazorCountry.Models
{
public class Continent
{
[Required, StringLength(2, MinimumLength = 2), Display(Name = "Code")]
[RegularExpression(#"[A-Z]+", ErrorMessage = "Only upper case characters are allowed.")]
public string ID { get; set; }
[Required, Display(Name = "Continent")]
public string Name { get; set; }
}
}
Country.cs:
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
namespace RazorCountry.Models
{
public class Country
{
[Required]
[StringLength(2, MinimumLength = 2)]
[RegularExpression(#"[A-Z]+", ErrorMessage = "Only upper case characters are allowed.")]
[Display(Name = "Code")]
public string ID { get; set; }
[Required]
[RegularExpression(#"[A-Z]+", ErrorMessage = "Only upper case characters are allowed.")]
[Display(Name = "Continent")]
public string ContinentID { get; set; }
[Required]
[Display(Name = "Country")]
public string Name { get; set; }
[Range(1, 10000000000)]
[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]
public int Population { get; set; }
public int Area { get; set; }
[Display(Name = "UN Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime UnitedNationsDate { get; set; }
}
}

Related

How insert multiple value in Intermediate table through API

I use to add value from the VUEJS where write code like this.
<multiselect v-model="schoolTypeform.schoolTypeId" :options="SchoolTypes" :multiple="true" :close-on-select="false" :clear-on-select="false" :preserve-search="true" placeholder="Pick School Type" label="name" track-by="name" :preselect-first="true">
and the JS code for this is written like this:
async addSchool() {
this.isbtnLoading = true;
this.isException = false;
await this.axios.post(this.school, this.form).then(response => {
this.addSchoolType(response.data);
})
},
async addSchoolType(id) {
this.isbtnLoading = true;
this.isException = false;
this.schoolTypeform.shoolId = id;
await this.axios.post(this.apiBasedUrl + '/SchoolsSchoolType', this.schoolTypeform).then(response => {
this.isbtnLoading = false;
});
Now my ER structure is given like this:
School:(Table1)
public partial class Schools
{
public Guid ID { get; set; }
public string Name{ get; set; }
// Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolType:(Table2)
public class SchoolType
{
public Guid Id { get; set; }
public string Name { get; set; }
//Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolsSchoolType (It is Intermediate table): Here the relation between the above is many to many.
public class SchoolsSchoolType
{
public Guid Id { get; set; }
public Guid ShoolId { get; set; }
public Schools Schools { get; set; }
public Guid SchoolTypeId { get; set; }
public SchoolType SchoolType { get; set; }
}
Here is repository method write for single value input, but I want to add here multiple value in the intermediates or junction table.
public async Task<Guid> CreateSchoolsAsync(SchoolsCreateVm schoolsCreateVm)
{
if (_GpsContext != null)
{
var schoolsEntity = new Schools()
{
ID = Guid.NewGuid(),
Name = schoolsCreateVm.Name,
SchoolsSchoolTypes = new List<SchoolsSchoolType>()
};
var schoolType = new SchoolType();
schoolsEntity.SchoolsSchoolTypes = new List<SchoolsSchoolType>
{
new SchoolsSchoolType
{
ShoolId =schoolsEntity.ID,
SchoolTypeId =schoolType.Id
}
};
return schoolsEntity.ID;
}
return Guid.Empty
}
Controller code is written here:
[HttpPost]
public async Task<IActionResult> PostSchool([FromBody]SchoolsCreateVm schoolsCreateVm)
{
var result = await _schoolsRepository.CreateSchoolsAsync(schoolsCreateVm);
if (result != null)
{
return Ok(result);
}
return NotFound();
}
Here is viewmodel used by me:
public class SchoolsCreateVm
{
public string Name { get; set; }
public List<Guid> SchoolTypeId{ get; set; } // List type of for intermediate table
public SchoolsCreateVm()
{
SchoolTypeId = new List<Guid>();
}
How can insert many schooltype for a single school in the intermediates(many to many) relation table through the VUEJS multiple selects.
Finally I am able to find the solution...
public async Task<Guid> CreateSchoolsAsync(SchoolsCreateVm schoolsCreateVm)
{
if (_GpsContext != null)
{
var schoolId = Guid.NewGuid();
var schoolsEntity = new Schools()
{
ID = schoolId, // 1--[1,2,3]
Name = schoolsCreateVm.Name,
};
// Here the code in which we can enter in the multiple table and Intermediate table
var SchoolsSchoolTypeList = new List<SchoolsSchoolType>();
foreach(var item in schoolsCreateVm.SchoolTypeId)
{
SchoolsSchoolTypeList.Add(new SchoolsSchoolType
{
Id = Guid.NewGuid(),
ShoolId = schoolId,
SchoolTypeId = item,
});
}
await _GpsContext.School.AddAsync(schoolsEntity);
_GpsContext.SchoolsSchoolTypes.AddRange(SchoolsSchoolTypeList);//Enter here for intermediate table that is 'SchoolsSchoolTypes'
await _GpsContext.SaveChangesAsync();
return schoolsEntity.ID;
}
return Guid.Empty;
}

how to update a table in sqlite corresponding to a id

i have 2 forms. first form saves value to company_master except 2 fields.In second form want to update company_master in sqlite when id=1 those 2 fileds.
in form2 i have tried simple update but it doesnot work
form1.xaml
private async void OnSave(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(ECompnyPhone.Text))
{
}
else
{
if (pickCompnyType.SelectedIndex == 0)
{
type = "Academic";
}
else if (pickCompnyType.SelectedIndex == 1)
{
type = "Financial";
}
if (pickYear.SelectedIndex == 0)
{
year = "April - March";
}
else if (pickYear.SelectedIndex == 1)
{
year = "January - December";
}
var cmpny = new COMPANY_MASTER
{
Name = ECompnyName.Text,
PhoneNo = ECompnyPhone.Text,
Email = ECompnyEmail.Text,
Address1 = ECompnyAdd1.Text,
Address2 = ECompnyAdd2.Text,
Address3 = ECompnyAdd3.Text,
Type = type,
Wing = EWing.Text,
Year = year
};
var checker = await _connection.InsertAsync(cmpny);
if (checker == 1)
{
await DisplayAlert("Message", "Data saved successfully.", "Ok");
await Navigation.PopAsync();
}
}
}
catch
{
await DisplayAlert("Error", "Error in data saving. Please retry later.", "Ok");
}
}
form2.xaml
private async void OnSave(object sender, EventArgs e)
{
try
{
var expense = new COMPANY_MASTER
{
Opening_Cash = Convert.ToDecimal(EOCash.Text),
Available_Cash = Convert.ToDecimal(EACash.Text)
};
var checker = await _connection.UpdateAsync(expense);
if (checker == 1)
{
await DisplayAlert("Message", "Data saved successfully.", "Ok");
await Navigation.PopAsync();
}
}
catch
{
await DisplayAlert("Error", "Error in data saving. Please retry later.", "Ok");
}
}
Company_master.cs
public class COMPANY_MASTER : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[PrimaryKey, AutoIncrement]
public int CompanyId { get; set; }
public string _name { get; set; }
public string _address1 { get; set; }
public string _address2 { get; set; }
public string _address3 { get; set; }
public string _email { get; set; }
public string _phoneNo { get; set; }
public string _type { get; set; }
public string _wing { get; set; }
public string _year { get; set; }
public decimal _openingcash { get; set; }
public decimal _availablecash { get; set; }
public decimal Available_Cash
{
get { return _availablecash; }
set
{
if (_availablecash == value)
return;
_availablecash = value;
OnPropertyChanged();
}
}
public decimal Opening_Cash
{
get { return _openingcash; }
set
{
if (_openingcash == value)
return;
_openingcash = value;
OnPropertyChanged();
}
}
public string Name
{
get { return _name; }
set
{
if (_name == value)
return;
_name = value;
OnPropertyChanged();
}
}
public string Year
{
get { return _year; }
set
{
if (_year == value)
return;
_year = value;
OnPropertyChanged();
}
}
public string Wing
{
get { return _wing; }
set
{
if (_wing == value)
return;
_wing = value;
OnPropertyChanged();
}
}
public string Type
{
get { return _type; }
set
{
if (_type == value)
return;
_type = value;
OnPropertyChanged();
}
}
public string PhoneNo
{
get { return _phoneNo; }
set
{
if (_phoneNo == value)
return;
_phoneNo = value;
OnPropertyChanged();
}
}
public string Address1
{
get { return _address1; }
set
{
if (_address1 == value)
return;
_address1 = value;
OnPropertyChanged();
}
}
public string Address2
{
get { return _address2; }
set
{
if (_address2 == value)
return;
_address2 = value;
OnPropertyChanged();
}
}
public string Address3
{
get { return _address3; }
set
{
if (_address3 == value)
return;
_address3 = value;
OnPropertyChanged();
}
}
public string Email
{
get { return _email; }
set
{
if (_email == value)
return;
_email = value;
OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
i want to update company_master's opening_cash and available_cash where companyid=1 in form2
now updation is not working
You can't update a new element
var expense = new COMPANY_MASTER
{
Opening_Cash = Convert.ToDecimal(EOCash.Text),
Available_Cash = Convert.ToDecimal(EACash.Text)
};
var checker = await _connection.UpdateAsync(expense); //here expense.companyid = 0
...
when you create a new object id is asigned with 0 value, for update id must exist in your table.

How to trigger App Center Push from my asp.net Web API?

I'm making an android Xamarin.Android. I finished the android application and now I want to add remote push notifications based on my item condition in my database that can accessed from ASP.Net Web Api.
I succeeded sent notifications from App Center Push to my application. I already authorized the App Center Client and now can access the app center api. I'm planning to merge the app center api to my asp.net web api if possible. But I don't know where to start it.
Should I put the app center action to my controller (I don't know if its working or not) or there's another way?
here's my controller:
public class InventoriesController : ApiController
{
private InventoryRepository _inventoryRepository;
public InventoriesController()
{
_inventoryRepository = new InventoryRepository();
}
// GET: api/Categories
public IHttpActionResult GetInventories()
{
IEnumerable<InventoryViewModel> inv = _inventoryRepository.GetAll().ToList().Select(e=> new InventoryViewModel(e)).ToList();
return Ok(inv);
}
// GET: api/Categories/5
[ResponseType(typeof(InventoryViewModel))]
public IHttpActionResult GetInventory(Guid id)
{
InventoryViewModel inventory = new InventoryViewModel (_inventoryRepository.GetSingle(e => e.Id == id));
if (inventory == null)
{
return NotFound();
}
return Ok(inventory);
}
// PUT: api/Categories/5
[ResponseType(typeof(void))]
public IHttpActionResult PutInventory(Guid id, InventoryViewModel inventory)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != inventory.Id)
{
return BadRequest();
}
try
{
_inventoryRepository.Edit(inventory.ToModel());
}
catch (DbUpdateConcurrencyException)
{
if (!InventoryExist(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Categories
[ResponseType(typeof(InventoryViewModel))]
public IHttpActionResult PostInventory(InventoryViewModel inventory)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_inventoryRepository.Add(inventory.ToModel());
}
catch (DbUpdateException)
{
if (InventoryExist(inventory.Id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = inventory.Id }, inventory);
}
// DELETE: api/Categories/5
[ResponseType(typeof(Inventory))]
public async Task<IHttpActionResult> DeleteInventory(Guid id)
{
Inventory inventory = _inventoryRepository.GetSingle(e => e.Id == id);
if (inventory == null)
{
return NotFound();
}
await _inventoryRepository.DeleteAsync(inventory);
return Ok(inventory);
}
private bool InventoryExist(Guid id)
{
IQueryable<Inventory> inv = _inventoryRepository.GetAll();
return inv.Count(e => e.Id == id) > 0;
}
And this is my model:
public class InventoryViewModel
{
public Guid Id { get; set; }
public int Quantity { get; set; }
public DateTime ExpirationDate { get; set; }
public bool IsDeleted { get; set; }
public bool IsConsumed { get; set; }
public decimal Price { get; set; }
public string ItemName { get; set; }
public Guid ProductId { get; set; }
public Guid StorageId { get; set; }
public string AddedUserId { get; set; }
public Inventory ToModel()
{
return new Inventory
{
Id = (Id == Guid.Empty) ? Guid.NewGuid() : Id,
ExpirationDate = ExpirationDate,
Price = Price,
ProductId=ProductId,
StorageId=StorageId,
ItemName=ItemName,
IsDeleted=IsDeleted,
IsConsumed=IsConsumed,
AddedUserId = AddedUserId,
};
}
public InventoryViewModel()
{
}
public InventoryViewModel(Inventory i)
{
this.Id = i.Id;
this.ExpirationDate = i.ExpirationDate;
this.Price = i.Price;
this.ProductId = i.ProductId;
this.StorageId = i.StorageId;
this.ItemName = i.ItemName;
this.AddedUserId = i.AddedUserId;
}
}
I want to make the app center send notification based on Expired Date on my Inventories model and AddedUserId. So its my web self made web api who send the notification to my apps.
I read this documentation: [https://learn.microsoft.com/en-us/appcenter/push/pushapi][1] but still don't know where I have to write in my Web Api.
Hope someone here can help me.
Thanks in advance :)
You can find detail here in appcenter REST API documentation
https://learn.microsoft.com/en-us/appcenter/push/rest-api
Appcenter REST API swagger: https://openapi.appcenter.ms/

Issue is why my Web API not returning JSON

see my web api controller actions. i am return a response class from my action which has wrapped customer data ,status and message etc. but when i am invoking my web action from browser then action returning this symbol {} only which is very odd. see my web api code
my code as follows
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
static readonly ICustomerRepository repository = new CustomerRepository();
[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
var Response=new Response(true, "SUCCESS", repository.GetAll());
//return Response;
//return Request.CreateResponse(HttpStatusCode.OK, Response);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
return response;
}
[HttpGet, Route("GetByID/{customerID}")]
public Response GetCustomer(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new Response(true, "SUCCESS", customer);
//return Request.CreateResponse(HttpStatusCode.OK, response);
}
[HttpGet, Route("GetByCountryName/{country}")]
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
public HttpResponseMessage PostCustomer(Customer customer)
{
customer = repository.Add(customer);
var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
response.Headers.Location = new Uri(uri);
return response;
}
public void PutProduct(string customerID, Customer customer)
{
customer.CustomerID = customerID;
if (!repository.Update(customer))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public void DeleteProduct(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
repository.Remove(customerID);
}
}
public class Response
{
bool IsSuccess = false;
string Message;
object ResponseData;
public Response(bool status, string message, object data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}
public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
}
this way i am calling from winform using httpclient
var baseAddress = "http://localhost:38762/api/customer/GetAll";
using (var client = new HttpClient())
{
using (var response = client.GetAsync(baseAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
var cust = JsonConvert.DeserializeObject<Response>(customerJsonString);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
tell me what is wrong in my code for GetAll actions which is not returning json rather return {}
i have to return my response class instead of IEnumerable<Customer> so show me the path what to change in code.
if my method looks like
[HttpGet, Route("GetAll")]
public Response GetAllCustomers()
{
var Response = new Response(true, "SUCCESS", repository.GetAll());
//return Response;
//return Request.CreateResponse(HttpStatusCode.OK, Response);
//HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
return Response;
}
OR
[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
var Response=new Response(true, "SUCCESS", repository.GetAll());
//return Response;
//return Request.CreateResponse(HttpStatusCode.OK, Response);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
return response;
}
but not returning any data or json. just return {} means null.
this way i give instruction to my web api as a result it should return json.
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
I think the issue could be that you are already sending SUCCESS in your Response then creating another response using the Request.CreateResponse(..) method.
You can try to modify your method as below
public Response GetAllCustomers()
{
var data = repository.GetAll();
if (data !=null)
return Request.CreateResponse(HttpStatusCode.OK, data);
else
return Request.CreateErrorResponse(HttpStatusCode.NotFound,"No records found");
}
You can return these
HttpStatusCodes

How to use split in linq query?

I am trying to call the following query string but I am getting 'no data' message on the client-side - 'api/data?id=786,899&price_type=cvr'.
public HttpResponseMessage Get([FromUri] Query query)
{
var data = db.database_ICs.AsQueryable();
if (query.id!= null)
{
data = data.Where(c => query.id.Split(',').Contains(c.ID));
}
if (query.price_type != null)
{
data = data.Where(c => c.Cover == query.price_type);
}
if (!data.Any())
{
var message = string.Format("No data was found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
public class Query
{
public string id{ get; set; }
public string price_type { get; set; }
public Nullable<DateTime> startDate { get; set; }
public Nullable<DateTime> endDate{ get; set; }
}
Any help would be very much appreciated.
Many Thanks.
var data = db.database_ICs.AsQueryable();
if (!string.IsNullOrEmpty(query.id))
{
var ids = query.id.Split(',').ToList();
data = data.Where(c => ids.Contains(c.ID));
}
Assuming c.ID and ids elements are of the same type of course.
Edit: one way of checking if you have the querystring or not

Resources