' INT []'不包含'包含'的定义

时间:2014-07-07 20:07:05

标签: c# linq asp.net-web-api

我正在尝试将数组int[]传递给我的函数,然后删除该数组中包含主键的所有记录。

此行.Where(t => personIds.Contains(t.PersonId)).ToList()会抛出错误:

'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

这是我的控制器:

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();
        }

  }
}

这是人物模型:

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; }
    }
}  

这是ProjectPerson链接表模型:

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;}
 }
}

1 个答案:

答案 0 :(得分:8)

问题是t.PersonId的类型int?我现在添加了.Value,它将问题行更改为.Where(t => personIds.Contains(t.PersonId.Value)).ToList()。这现在有效:

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();
        }