如何查找在asp.net中具有特定布尔列值true的SQL数据库中的所有行?
问题描述:
我有一个表有两个布尔列:isActive和isAcceptingParticipants。如何查找在asp.net中具有特定布尔列值true的SQL数据库中的所有行?
我想获得所有这些行都是真的。
我已经在下面包含模型文件和我想要的服务的部分实现。
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectTracker.Models
{
public class Project
{
[Key]
public int Id { get; set; }
public int CountParticipants { get; set; }
public int CountActiveParticipants { get; set; }
public Boolean isActive { get; set; }
public Boolean isAcceptingParticipants { get; set; }
public int WhoseTurn { get; set; }
}
}
这就是我想要实现GetInProgress这将返回有isActive和isAccepting参与者均为真正的全行服务模块。
using ProjectTracker.Models;
using System.Collections.Generic;
using System;
using ProjectTracker.Data;
using System.Linq;
namespace ProjectTracker.Services
{
public interface IProjectData
{
IEnumerable<Project> GetAcceptingParticipants();
IEnumerable<Project> GetInProgress();
Project ParticipatingIn(int id); //Pass userId to this, returns the project that the user is part of
Project Add(Project newProject);
Project Get(int id);
void Delete(int id);
void Commit();
}
public class SqlProjectData : IProjectData
{
private ApplicationDbContext _context;
public SqlProjectData(ApplicationDbContext context)
{
_context = context;
}
public Project Add(Project newProject)
{
_context.Add(newProject);
Commit();
return newProject;
}
public void Commit()
{
_context.SaveChanges();
}
public void Delete(int id)
{
var toBeDeleted = Get(id);
if (toBeDeleted == null) return;
_context.Remove<Project>(toBeDeleted);
}
public Project Get(int id)
{
return _context.Project.FirstOrDefault(r => r.Id == id);
}
public IEnumerable<Project> GetAcceptingParticipants()
{
throw new NotImplementedException();
}
public IEnumerable<Project> GetInProgress()
{
throw new NotImplementedException();
}
public Project ParticipatingIn(int id)
{
throw new NotImplementedException();
}
}
}
答
您可以简单地使用LINQ:
return _context.Project.Where(r => r.isActive && r.isAcceptingParticipants);
答
public IEnumerable<Project> GetInProgress()
{
return _context.Project.Where(r => r.isActive && r.isAcceptingParticipants).ToList();
}
+0
尽管此代码可能会回答问题,但提供有关如何解决问题和/或为何解决问题的其他上下文会提高答案的长期价值。 –
需要.ToList()添加为方法的返回可枚举 – ISHIDA
@ISHIDA哦,不,他的方法返回一个IEnumerable的''所以你不要不需要那个。 –
Tvde1
这就是我正在寻找的,TY! – islingrad