【问题标题】:Query Using Entity Framework Error with Database Table name ErrorQuery Using Entity Framework Error with Database Table name Error
【发布时间】:2014-03-24 05:10:12
【问题描述】:

我想在 C# 中获取一些数据库数据。 但是我的 LINQ Query 连接的数据库表无效。

DataContext.cs

namespace BlackBoxSOS.Models
{
  public class DataContext : DbContext 
  {

    public DbSet<ServiceIdentification> ServiceIdentifications { get; set; }
    public DbSet<ObservationDatum> ObservationData { get; set; }

    ....

  }
}

Service.svc.cs 中的函数

public GetObservationResponseTypeMessage GetObservation(GetObservationTypeMessage request)
    {

        DataContext dataContext = new DataContext();

            var result = dataContext.ObservationData;

            ....
        return ...;
    }

变量结果是“SELECT [Extent1].[Id] AS [Id], [Extent1].[Res_Value] AS [Res_Value] FROM [dbo].[ObservationDatums] AS [Extent1]" 执行我的代码时。但 DataContext 有 DbSet ObservationData,而不是 ObservationDatums。

为什么这个程序有错误?我该如何解决?

【问题讨论】:

    标签: c# sql linq entity-framework


    【解决方案1】:

    您可以通过将表属性应用到 ObservationDatum 类型,或使用 Fluent API(覆盖 DbContext 中的 OnModelCreating)来自定义实体框架代码使用的表名。

    例如:

    [Table("ObservationData")]
    public class ObservationDatum
    {
    }
    

    或者:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ObservationDatum>().ToTable("ObservationData");
    }
    

    【讨论】:

    • 我更改了您建议我的代码。但是,运行Update-Databse -ConnectionStringName MyConnection 得到错误Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong. 我不知道我错过了什么。
    • 如果您要更改代码优先模型,那么您需要运行 Add-Migration 来构建更改,然后更新数据库,除非您已删除并重新创建了数据库。
    【解决方案2】:

    如果您的所有表名都是单数,您可以尝试在 DbContext 中使用以下代码禁用表名复数:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
    

    【讨论】:

    • 感谢您的建议。但是数据库表名是 ObservationData。
    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多