C# 序列包含多个匹配元素错误

C# 序列包含多个匹配元素错误,c#,asp.net-mvc,entity-framework-6,C#,Asp.net Mvc,Entity Framework 6,我有MVC5和EF6项目 在我的存储库中,我有数据库中“获取所有作业”的代码片段 public List<Job> GetAllJob() { if (_job.Any()) { var r = (from j in _job where j.JobStatus == 1 select j).ToList(); return r;

我有MVC5和EF6项目

在我的存储库中,我有数据库中“获取所有作业”的代码片段

 public List<Job> GetAllJob()
        {

            if (_job.Any())
            {
                var r = (from j in _job where j.JobStatus == 1 select j).ToList();
                return r;
                //return _job.Where(j => j.JobStatus==1).ToList();
            }
            else
            {
                return null;
            }
        }
堆栈跟踪:

   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass24f.<FindAlteredColumns>b__246(<>f__AnonymousType2b`2 <>h__TransparentIdentifier241)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Any[TSource](IQueryable`1 source)
   at ServiceLayer.JobService.GetAllJob() in C:\Users\MRT\Desktop\Final\MapWeb - Copy\ServiceLayer\JobService.cs:line 33
   at WebMap.Controllers.HomeController.Index() in C:\Users\MRT\Desktop\Final\MapWeb - Copy\WebMap\Controllers\HomeController.cs:line 25
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1源,Func`2谓词)
位于System.Data.Entity.Migrations.Infrastructure.EdmModelDifference.c__DisplayClass24f.b__246(f__匿名类型2B`2 h__透明标识符241)
在System.Linq.Enumerable.WhereSelectEnumerableInterator`2.MoveNext()中
在System.Linq.Enumerable.WhereSelectEnumerableInterator`2.MoveNext()中
位于System.Collections.Generic.List`1..ctor(IEnumerable`1集合)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
位于System.Data.Entity.Migrations.Infrastructure.EdmModelDifference.Diff(ModelMetadata源、ModelMetadata目标、Lazy`1 modificationCommandTreeGenerator、MigrationSqlGenerator MigrationSqlGenerator、String sourceModelVersion、String targetModelVersion)
位于System.Data.Entity.Migrations.Infrastructure.EdmModelDifferent.Diff(XDocument sourceModel,XDocument targetModel,Lazy`1 modificationCommandTreeGenerator,MigrationSqlGenerator MigrationSqlGenerator,String sourceModelVersion,String targetModelVersion)
位于System.Data.Entity.Migrations.DbMigrator.isModelOutdate(XDocument model,DbMigration lastMigration)
位于System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations,String targetMigrationId,String lastMigrationId)
位于System.Data.Entity.Migrations.Dbmigator.UpdateInternal(字符串targetMigration)
在System.Data.Entity.Migrations.DbMigrator.c__DisplayClassc.b__b()中
位于System.Data.Entity.Migrations.Dbmigator.EnsureDatabaseExists(操作必须成功才能访问数据库)
位于System.Data.Entity.Migrations.DbMigrator.Update(字符串targetMigration)
位于System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext上下文)
在System.Data.Entity.Internal.InternalContext.c__DisplayClassf`1.b__e()中
位于System.Data.Entity.Internal.InternalContext.PerforminizationAction(操作操作)
位于System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()处
位于System.Data.Entity.Internal.LazyInternalContext.b_uu4(InternalContext c)
在System.Data.Entity.Internal.RetryAction`1.PerformAction(输入)
位于System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 Action)
在System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()中
位于System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型entityType)
位于System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
位于System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
位于System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Any[TSource](IQueryable`1 source)
在C:\Users\MRT\Desktop\Final\MapWeb-Copy\ServiceLayer\JobService.cs中的ServiceLayer.JobService.GetAllJob()处:第33行
在C:\Users\MRT\Desktop\Final\MapWeb-Copy\WebMap\Controllers\HomeController.cs中的WebMap.Controllers.HomeController.Index()处:第25行
在lambda_方法中(闭包、控制器基、对象[])
位于System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object[]参数)
位于System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext ControllerContext,IDictionary`2参数)
位于System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext ControllerContext,ActionDescriptor ActionDescriptor,IDictionary`2参数)
在System.Web.Mvc.Async.AsyncControllerActionInvoker.b_u39(IAsyncResult asyncResult,ActionInvokeInnerInvokeState)
位于System.Web.Mvc.Async.AsyncResultRapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
位于System.Web.Mvc.Async.AsyncResultRapper.WrappedAsyncResultBase`1.End()
位于System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
在System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()中
在System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.c__DisplayClass46.b__3f()中
迁移历史记录表:

这是Job DomainClasse:

 public partial class Job
    {
        //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        //public Job()
        //{
        //    Channels = new Channel();
        //    Products = new HashSet<Product>();
        //}

        public long JobId { get; set; }

        public long UserId { get; set; }

        [Required]
        [StringLength(50)]


        public string JobName { get; set; }

        [StringLength(150)]

        public string JobDescripton { get; set; }
        [Index("IX_Jobs", order: 2)]
        public long JobCategoryId { get; set; }

        [Required]
        [StringLength(500)]


        public string JobAddress { get; set; }

        [Required]
        [StringLength(10)]


        public string JobPhone { get; set; }

        [StringLength(500)]


        public string JobImgUrl { get; set; }

        [Column(TypeName = "date")]
        public DateTime JobTimeRegister { get; set; }

        [Required]
        [StringLength(50)]
        public string JobLogLat { get; set; }

        public byte JobStatus { get; set; }
        [Index("IX_Jobs",order:1)]


        public int ShahrestanId { get; set; }
        [ScaffoldColumn(false)]
        public long ChannelId { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual Channel Channels { get; set; }

        public virtual JobCategory JobCategory { get; set; }

        public virtual Tbl_Shahrestan Tbl_Shahrestan { get; set; }

        public virtual User User { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Product> Products { get; set; }
    }
公共部分类作业
{
//[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”,“CA2214:DoNotCallOverridableMethodsInConstructors”)]
//公职()
//{
//通道=新通道();
//Products=新的HashSet();
//}
公共长作业ID{get;set;}
公共长用户标识{get;set;}
[必需]
[长度(50)]
公共字符串JobName{get;set;}
[长度(150)]
公共字符串JobDescripton{get;set;}
[索引(“IX_作业”,顺序:2)]
公共长作业类别ID{get;set;}
[必需]
[长度(500)]
公共字符串作业地址{get;set;}
[必需]
[条次建议修正案(10)]
公用字符串JobPhone{get;set;}
[长度(500)]
公共字符串JobImgUrl{get;set;}
[列(TypeName=“日期”)]
公共日期时间作业时间寄存器{get;set;}
[必需]
[长度(50)]
公共字符串JobLogLat{get;set;}
公共字节作业状态{get;set;}
[索引(“IX_作业”,顺序:1)]
public int ShahrestanId{get;set;}
[脚手架立柱(假)]
公共长ChannelId{get;set;}
[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”,“CA2227:CollectionPropertiesShouldBreadOnly”)]
公共虚拟通道通道{get;set;}
公共虚拟作业类别作业类别{get;set;}
公共虚拟Tbl_Shahrestan Tbl_Shahrestan{get;set;}
公共虚拟用户用户{get;set;}
[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”,“CA2227:CollectionPropertiesShouldBeRe
 public partial class Job
    {
        //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        //public Job()
        //{
        //    Channels = new Channel();
        //    Products = new HashSet<Product>();
        //}

        public long JobId { get; set; }

        public long UserId { get; set; }

        [Required]
        [StringLength(50)]


        public string JobName { get; set; }

        [StringLength(150)]

        public string JobDescripton { get; set; }
        [Index("IX_Jobs", order: 2)]
        public long JobCategoryId { get; set; }

        [Required]
        [StringLength(500)]


        public string JobAddress { get; set; }

        [Required]
        [StringLength(10)]


        public string JobPhone { get; set; }

        [StringLength(500)]


        public string JobImgUrl { get; set; }

        [Column(TypeName = "date")]
        public DateTime JobTimeRegister { get; set; }

        [Required]
        [StringLength(50)]
        public string JobLogLat { get; set; }

        public byte JobStatus { get; set; }
        [Index("IX_Jobs",order:1)]


        public int ShahrestanId { get; set; }
        [ScaffoldColumn(false)]
        public long ChannelId { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual Channel Channels { get; set; }

        public virtual JobCategory JobCategory { get; set; }

        public virtual Tbl_Shahrestan Tbl_Shahrestan { get; set; }

        public virtual User User { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Product> Products { get; set; }
    }
modelBuilder.Entity<Job>()
                .HasOptional(e => e.Channels)
                .WithRequired(e => e.Job)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Job>()
                .HasMany(e => e.Products)
                .WithRequired(e => e.Job)
                .WillCascadeOnDelete(false);
namespace ServiceLayer
{
    public class JobService : IJobService
    {
        private IUnitOfWork _uow;
        private IDbSet<Job> _job;
        private IUserService _userService;


        public JobService(IUnitOfWork uow, IUserService userService)
        {
            _uow = uow;
            _userService = userService;
            _job = _uow.Set<Job>();
        }


        public List<Job> GetAllJob()
        {

            if (_job.Any())
            {
                var r = (from j in _job where j.JobStatus == 1 select j).ToList();
                return r;
                //return _job.Where(j => j.JobStatus==1).ToList();
            }
            else
            {
                return null;
            }
        }

        public List<Job> GetAllJobsOneUser(string username)
        {
            User user = _userService.GetCurrentUser(username);
            List<Job> jobs = (from j in _job where j.User.UserId == user.UserId select j).ToList();
            _userService.GetOneUserAndEnCryptData(user);
            _uow.MarkAsChanged(user);
            return jobs;
        }

        public Job GetOneJobOneUser(long? jobId, string username)
        {
            if (jobId == null || jobId <= 0)
                return null;
            User user = _userService.GetCurrentUser(username);
            Job job = (from j in _job where j.User.UserId == user.UserId && j.JobId == jobId select j).SingleOrDefault();
            _userService.GetOneUserAndEnCryptData(user);
            _uow.MarkAsChanged(user);

            return job ;
        }

        public bool AddOneJobOneUser(Job job, HttpPostedFileBase JobImgUrl, string username)
        {
            User user = _userService.GetCurrentUser(username);
            job.JobStatus = (byte)ConfirmationStatus.Pending;
            job.UserId = user.UserId;
            job.JobTimeRegister = DateTime.Now;

            if (JobImgUrl != null) 
            {


                if (JobImgUrl.ContentLength > 51200000) 
                {

                    //return View();
                    return false;
                }
                if (JobImgUrl.ContentType != "image/jpeg") 
                {


                    return false;
                }

                Random rnd = new Random();
                string RndImageFileName = rnd.Next().ToString() + ".jpg";

                JobImgUrl.SaveAs(Path.Combine(HttpContext.Current.Server.MapPath("~") + "Upload/Imgs/Job/" + RndImageFileName));

                job.JobImgUrl = RndImageFileName; 
            }
            _job.Add(job);
            _userService.GetOneUserAndEnCryptData(user);
            _uow.MarkAsChanged(user);
            return true;
        }

        public bool EditOneJobOneUser(string username, Job job, HttpPostedFile ProductImageUrl)
        {
            try
            {

                var q = GetOneJobOneUser(job.JobId, username);
                if (q != null)
                {

                    if (ProductImageUrl != null)
                    {

                        if (System.IO.File.Exists(Path.Combine(HttpContext.Current.Server.MapPath("~") + "Upload/Imgs/Job/" +job.JobImgUrl)))

                        {
                            System.IO.File.Delete(Path.Combine(HttpContext.Current.Server.MapPath("~") + "Upload/Imgs/Job/" +job.JobImgUrl));
                        }
                        Random rnd = new Random();

                        q.JobImgUrl = rnd.Next().ToString() + ".jpg";
                        ProductImageUrl.SaveAs(Path.Combine(HttpContext.Current.Server.MapPath("~") + "Upload/Imgs/Product/" + q.JobImgUrl));

                    }
                    q.JobStatus = (byte) ConfirmationStatus.Pending;
                    q.JobTimeRegister = DateTime.Now;
                    q.ShahrestanId = job.ShahrestanId;
                }

                User user = _userService.GetCurrentUser(username);

                if (q.UserId == user.UserId)
                {
                    _job.Attach(q);
                    _uow.MarkAsChanged(q);
                    _userService.GetOneUserAndEnCryptData(user);
                    _uow.MarkAsChanged(user);
                    return true;
                }
                else
                {
                    _userService.GetOneUserAndEnCryptData(user);
                    _uow.MarkAsChanged(user);
                    return false;
                }


            }
            catch (Exception e)
            {
                var str = e.Message;
                return false;
            }
        }

        public bool RemoveOneJobOneUser(long? jobId,string username)
        {
            if (jobId == null || jobId <= 0)
                return false;
            try
            {
            Job job = (from j in _job where  j.User.Mobile == username && j.JobId == jobId  select j).SingleOrDefault(); 

            if (job == null)
                return false;

                _job.Remove(job);
                return true;
            }
            catch
            {

                return false;
            }



        }

        public Job GetOneJobOneUser(long userId, long jobId)
        {
            return (from j in _job where j.JobId == jobId && j.User.UserId == userId select j).SingleOrDefault();
        }

        public Job GetOneActiveJob(long? jobId)
        {
            if (jobId == null || jobId <= 0)
                return null;
            return (from j in _job where j.JobStatus.Equals(1) && j.JobId==jobId select j).FirstOrDefault();
        }


        public bool CheckJobExist(string username)
        {
            List<Job> existJob=GetAllJobsOneUser(username);
            if (existJob == null)
                return false;
            else
                return true;
        }
    }
}