I am trying to pass an array int[]
to my function, then delete all records with a primary key in that array.
This line .Where(t => personIds.Contains(t.PersonId)).ToList()
throws the error:
'int[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource)' has some invalid arguments
This is my controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Hercules.WebApi.Models;
namespace Hercules.WebApi.Controllers
{
public class TicketController : ApiController
{
private MyWebApiContext db = new MyWebApiContext();
[Route("Ticket/removeTicketPeople")]
public void RemoveTicketPeople([FromUri]int ticketId, [FromBody]int[] personIds)
{
db.TicketPeople.Where(t => t.TicketId == ticketId)
.Where(t => personIds.Contains(t.PersonId)).ToList()
.ForEach(t => db.TicketPeople.Remove(t));
db.SaveChanges();
}
}
}
This is the Person Model:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Hercules.WebApi.Models
{
public class Person
{
[Key]
public int PersonId { get; set; }
// Properties
public String Firstname { get; set; }
public String Surname { get; set; }
}
}
This is the ProjectPerson link table model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Hercules.WebApi.Models
{
public class ProjectPerson{
[Key]
public int ProjectPersonId { get; set; }
[ForeignKey("Project")]
public int? ProjectId {get;set;}
public virtual Project Project { get; set; }
[ForeignKey("Person")]
public int? PersonId {get;set;}
public virtual Person Person {get;set;}
public string RelationshipType {get;set;}
}
}
The problem is the the type of t.PersonId
was int?
I have now added .Value
which changed the problem line to .Where(t => personIds.Contains(t.PersonId.Value)).ToList()
. This now works:
public void RemoveTicketPeople([FromUri]int ticketId, [FromBody]int[] personIds)
{
db.TicketPeople.Where(t => t.TicketId == ticketId)
.Where(t => personIds.Contains( t.PersonId.Value)).ToList()
.ForEach(t => db.TicketPeople.Remove(t));
db.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With