如何手动创建数据库模型?

How to create Database Model manually?

我有一个现有的 PostgreSQL 数据库,我想为 table 手动创建模型,因为脚手架不起作用。为什么 运行 db.CDRs.First(); 抛出异常?

Program.cs:

        ...
        using (var db = new Model.CDRContext())
        {
            var cdr = db.CDRs.First(); // Exception has occurred here
        }
        ...

CDRContext.cs:

    ...
public class CDRContext : DbContext
{
    public DbSet<CallDataRecord> CDRs { get; set; }


    string DB_SERVER = "127.0.0.1";
    string USER = "x";
    string PASSWORD = "x";
    string DATABASE = "x";
    int PORT = 3306; 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseNpgsql($"Host={DB_SERVER};Username={USER}; Port={PORT};Password={PASSWORD};Database={DATABASE};");
}
    ...

这是来自调试控制台的详细异常 window:

Unhandled exception. Npgsql.PostgresException (0x80004005): 42P01: relation "CDRs" does not exist at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming) at Npgsql.NpgsqlDataReader.NextResult() at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior) at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader() at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.InitializeReader(DbContext _, Boolean result) at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.First[TSource](IQueryable1 source) at EFGetStarted.Program.Main(String[] args) in c:\Development\EFGetStarted\Program.cs:line 17 Exception data: Severity: ERROR SqlState: 42P01 MessageText: relation "CDRs" does not exist Position: 45 File: parse_relation.c Line: 894 Routine: parserOpenTable

尝试更改 DbSet 的名称 'CDRs' 以匹配上下文中的数据库名称 table ('CallDataRecord'?)。我看到的 PostgreSQL 数据库优先或代码优先的示例是以这种方式设置的,错误消息是由于它寻找不存在的 table CDR。

  public DbSet<CallDataRecord> YourDbTableName{ get; set; }