我有mvc 5和ef 6项目
在我的存储库中,我有代码片段,用于获取我数据库中的所有作业
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;
}
}
执行时间,当编译器到达Any()方法时,请告诉我这个错误:
序列包含多个匹配元素
System.InvalidOperationException:
{System.InvalidOperationException: Sequence contains more than one matching element
堆栈跟踪:
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()
迁移历史记录表:
这是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; }
}
的DbContext:
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);
知道什么时候执行Entityframework命令(特别是update-database,add-migration)给我一个错误:
序列包含多个匹配元素
我不知道为什么会给我这个错误
----更新为singleOrDefault Querys添加JobService ----
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;
}
}
}
但是当我将singleOrDefualt更改为FirstOrDefault时仍然会出现错误