实体框架查询未返回正确的结果

时间:2017-03-07 03:00:39

标签: entity-framework visual-studio tsql asp.net-core

我正在尝试在我的web api上传递带有实体框架的原始sql连接。这是我的api代码。

namespace HannaOilAndGas2.Controllers
{
    [Produces("application/json")]
    [Route("api/mainview")]
    public class MainViewApi : Controller
    {

        private readonly ScadaContext _context;

        public MainViewApi(ScadaContext context)
        {
            _context = context;
        }

        // GET: api/values
        [HttpGet]
        [Route("allmainview")]
        public IEnumerable<Device> GetAllMainView()
        {

            return _context.Device.FromSql(
                "SELECT PD.RecId, D.Location, Round(PD.SPOT_FLOW_RATE,0), Round(PD.PREVIOUS_DAY_VOLUME,0)," +
                "Round(PD.LINE_PRESSURE,0), Round(PD.DIFFERENTIAL_PRESSURE,0), Round(PD.TEMPERATURE,0)," +
                "Round(PD.BATTERY_VOLTAGE,0) ROUND(PD.FCP,0), ROUND(PD.FTP,0) D.LAST_COMMUNICATION, D.LAST_COMMUNICATION_METHOD" +
                "FROM DEVICE D" +
                "JOIN POLL_DATA PD" +
                "ON D.HANNA_DEVICE_ID = PD.HANNA_DEVICE_ID").Where(x => x.MeterId != "HOGC%"); 
        }

我的设备模型看起来像这样,因为所有这些表都与设备

相关
namespace HannaOilAndGas2.Data
{
    public partial class Device
    {
        public Device()
        {
            DailyData = new HashSet<DailyData>();
            PollBattery = new HashSet<PollBattery>();
            PollDifferentialPressure = new HashSet<PollDifferentialPressure>();
            PollFcp = new HashSet<PollFcp>();
            PollFtp = new HashSet<PollFtp>();
            PollLinePressure = new HashSet<PollLinePressure>();
            PollPdVolume = new HashSet<PollPdVolume>();
            PollSpotFlowRate = new HashSet<PollSpotFlowRate>();
            PollTemperature = new HashSet<PollTemperature>();
            PollData = new HashSet<PollData>();
            ChokeHistory = new HashSet<ChokeHistory>();
            CommentsHistory = new HashSet<CommentsHistory>();
            ContractHourHistory = new HashSet<ContractHourHistory>();
            HourlyData = new HashSet<HourlyData>();
            MeterTubeSizeHistory = new HashSet<MeterTubeSizeHistory>();
            OrificeCoeffHistory = new HashSet<OrificeCoeffHistory>();
            PlateSizeHistory = new HashSet<PlateSizeHistory>();
            PollDataHistorical = new HashSet<PollDataHistorical>();
            ShutinHistory = new HashSet<ShutinHistory>();
        }

        public int HannaDeviceId { get; set; }
        public int? MdbDeviceId { get; set; }
        public string SpreadsheetId { get; set; }
        public string SpectraId { get; set; }
        public string ServiceStarId { get; set; }
        public string MeterId { get; set; }
        public string Location { get; set; }
        public float? ShutinPressure { get; set; }
        public float? Latitude { get; set; }
        public float? Longitude { get; set; }
        public float? Choke { get; set; }
        public float? OrificeCoeff { get; set; }
        public decimal? MeterTubeSize { get; set; }
        public float? ContractHour { get; set; }
        public string SecTwnRange { get; set; }
        public string County { get; set; }
        public string State { get; set; }
        public decimal? PlateSize { get; set; }
        public string Comments { get; set; }
        public DateTime? LastCommunication { get; set; }
        public string LastCommunicationMethod { get; set; }

        public virtual ICollection<DailyData> DailyData { get; set; }
        public virtual ICollection<PollBattery> PollBattery { get; set; }
        public virtual ICollection<PollDifferentialPressure> PollDifferentialPressure { get; set; }
        public virtual ICollection<PollFcp> PollFcp { get; set; }
        public virtual ICollection<PollFtp> PollFtp { get; set; }
        public virtual ICollection<PollLinePressure> PollLinePressure { get; set; }
        public virtual ICollection<PollPdVolume> PollPdVolume { get; set; }
        public virtual ICollection<PollSpotFlowRate> PollSpotFlowRate { get; set; }
        public virtual ICollection<PollTemperature> PollTemperature { get; set; }
        public virtual ICollection<PollData> PollData { get; set; }
        public virtual ICollection<ChokeHistory> ChokeHistory { get; set; }
        public virtual ICollection<CommentsHistory> CommentsHistory { get; set; }
        public virtual ICollection<ContractHourHistory> ContractHourHistory { get; set; }
        public virtual ICollection<HourlyData> HourlyData { get; set; }
        public virtual ICollection<MeterTubeSizeHistory> MeterTubeSizeHistory { get; set; }
        public virtual ICollection<OrificeCoeffHistory> OrificeCoeffHistory { get; set; }
        public virtual ICollection<PlateSizeHistory> PlateSizeHistory { get; set; }
        public virtual ICollection<PollDataHistorical> PollDataHistorical { get; set; }
        public virtual ICollection<ShutinHistory> ShutinHistory { get; set; }

    }
}

这是我的背景

 public partial class ScadaContext : DbContext
    {
        public ScadaContext(DbContextOptions<ScadaContext> options) : base(options)
        {}

        public ScadaContext()
        {
        }

        public virtual DbSet<ChokeHistory> ChokeHistory { get; set; }
        public virtual DbSet<CommentsHistory> CommentsHistory { get; set; }
        public virtual DbSet<ContractHourHistory> ContractHourHistory { get; set; }
        public virtual DbSet<DailyData> DailyData { get; set; }
        public virtual DbSet<Device> Device { get; set; }
        public virtual DbSet<HourlyData> HourlyData { get; set; }
        public virtual DbSet<MeterTubeSizeHistory> MeterTubeSizeHistory { get; set; }
        public virtual DbSet<OrificeCoeffHistory> OrificeCoeffHistory { get; set; }
        public virtual DbSet<PlateSizeHistory> PlateSizeHistory { get; set; }
        public virtual DbSet<PollBattery> PollBattery { get; set; }
        public virtual DbSet<PollData> PollData { get; set; }
        public virtual DbSet<PollDataHistorical> PollDataHistorical { get; set; }
        public virtual DbSet<PollDifferentialPressure> PollDifferentialPressure { get; set; }
        public virtual DbSet<PollFcp> PollFcp { get; set; }
        public virtual DbSet<PollFtp> PollFtp { get; set; }
        public virtual DbSet<PollLinePressure> PollLinePressure { get; set; }
        public virtual DbSet<PollPdVolume> PollPdVolume { get; set; }
        public virtual DbSet<PollSpotFlowRate> PollSpotFlowRate { get; set; }
        public virtual DbSet<PollTemperature> PollTemperature { get; set; }
        public virtual DbSet<ShutinHistory> ShutinHistory { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ChokeHistory>(entity =>
            {
                entity.HasKey(e => e.RecId)
                    .HasName("PK_CHOKE_HISTORY");

                entity.ToTable("CHOKE_HISTORY");

                entity.Property(e => e.RecId).HasColumnName("RecID");

                entity.Property(e => e.Choke).HasColumnName("CHOKE");

                entity.Property(e => e.HannaDeviceId).HasColumnName("HANNA_DEVICE_ID");

                entity.Property(e => e.ImportMethod)
                    .IsRequired()
                    .HasColumnName("IMPORT_METHOD")
                    .HasMaxLength(50);

                entity.Property(e => e.Timestamp)
                    .HasColumnName("TIMESTAMP")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("getdate()");

                entity.HasOne(d => d.HannaDevice)
                    .WithMany(p => p.ChokeHistory)
                    .HasForeignKey(d => d.HannaDeviceId)
                    .HasConstraintName("FK_CHOKE_HISTORY_DEVICE");
            });

我的所有表都设置在此之后我想让api中的查询工作但是我得到的所有表都是[]的空结果。我对实体框架相当新,我读过你可以做那样的原始sql。我不确定我做错了什么任何帮助将不胜感激。我的应用程序是.net核心1.1应用程序。

2 个答案:

答案 0 :(得分:1)

只需在此处替换where条款:

Where(x => x.MeterId != "HOGC%")

......就像这样:

Where(x => !x.MeterId.Startswith("HOGC"))

这将像SQL中的NOT LIKE一样(由于!运算符)。

答案 1 :(得分:1)

使用原始SQL查询时需要注意几个限制:

  • SQL查询只能用于返回属于的实体类型 你的模特。我们的积压工作有一项增强功能可以启用 从原始SQL查询返回ad-hoc类型。

  • SQL查询必须返回实体类型的所有属性的数据。

  • 结果集中的列名必须与列名相匹配 属性映射到。注意这与EF6.x不同 原始SQL查询和结果忽略了属性/列映射 设置列名称必须与属性名称匹配。

  • SQL查询不能包含相关数据。但是,在很多情况下你 可以使用Include运算符在查询之上进行组合以返回 相关数据(见包括相关数据)。

https://docs.microsoft.com/en-us/ef/core/querying/raw-sql

您可以将Dapper liberary用于原始sql或使用Linq查询。