我正在深入研究 linq2db 的一个小项目。我已经设置了模型、连接和简单的查询。但事情是这样的:每次运行查询时,linq2db 都会使用实体模型中的表名称,而不是 fluencemapper 中的名称。我是否遗漏了有关使用 MappingSchema() 和 FlumentMappingBuilder 的信息?帮助 linq2db 的新手吗? 🤔 我使用 sqlite 数据库...
public class SparkleContext : DataConnection
{
public SparkleContext(DataOptions<SparkleContext> options)
: base(options.Options)
{
AddMappingSchema(new SparkleMappingSchema());
}
public ITable<CompanyEm> Companies => this.GetTable<CompanyEm>();
public ITable<MeterEm> Meters => this.GetTable<MeterEm>();
public ITable<ReadingsEm> Readings => this.GetTable<ReadingsEm>();
}
和映射模式
public class SparkleMappingSchema : MappingSchema
{
public SparkleMappingSchema()
{
var mappings = new MappingSchema();
var builder = new FluentMappingBuilder(mappings);
builder.Entity<CompanyEm>().HasTableName("Companies")
.Property(x => x.Id).HasColumnName("Id").IsIdentity().IsPrimaryKey()
.Property(x => x.Name).HasColumnName("Name").IsNotNull()
.Property(x => x.Description).HasColumnName("Description").IsNullable()
.Property(x => x.Meters).HasColumnName("Meters").IsNullable()
.Property(x => x.CreatedAt).HasColumnName("CreatedAt").IsNullable()
.Property(x => x.UpdatedAt).HasColumnName("UpdatedAt").IsNullable();
builder.Entity<MeterEm>().HasTableName("Meters")
.Property(x => x.Id).HasColumnName("Id").IsIdentity().IsPrimaryKey()
.Property(x => x.Name).HasColumnName("Name").IsNotNull()
.Property(x => x.Readings).HasColumnName("Readings").IsNullable()
.Property(x => x.CreatedAt).HasColumnName("CreatedAt").IsNullable()
.Property(x => x.UpdatedAt).HasColumnName("UpdatedAt").IsNullable();
builder.Entity<ReadingsEm>().HasTableName("Readings")
.Property(x => x.Id).HasColumnName("Id").IsIdentity().IsPrimaryKey()
.Property(x => x.Time).HasColumnName("Time").IsNotNull()
.Property(x => x.Value).HasColumnName("Value").IsNotNull()
.Property(x => x.CreatedAt).HasColumnName("CreatedAt").IsNullable()
.Property(x => x.UpdatedAt).HasColumnName("UpdatedAt").IsNullable();
}
}
和小查询
using var sparkleDb = new DataConnection(context.DataProvider, context.ConnectionString);
var test = context.Companies.Where(x => x.Name == "God_Company").Select(x => x.Id).AsQueryable();
错误是这样的 System.Data.SQLite.SQLiteException: 'SQL 逻辑错误 没有这样的表:CompanyEm'
这是因为你定义了错误的映射
MappingSchema
。使用 FluentMappingBuilder
参数创建 this
。
public class SparkleMappingSchema: MappingSchema
{
public SparkleMappingSchema()
{
var builder = new FluentMappingBuilder(this);
builder.Entity<CompanyEm>().HasTableName("Companies")
.Property(x => x.Id).HasColumnName("Id").IsIdentity().IsPrimaryKey()
.Property(x => x.Name).HasColumnName("Name").IsNotNull()
.Property(x => x.Description).HasColumnName("Description").IsNullable()
.Property(x => x.Meters).HasColumnName("Meters").IsNullable()
.Property(x => x.CreatedAt).HasColumnName("CreatedAt").IsNullable()
.Property(x => x.UpdatedAt).HasColumnName("UpdatedAt").IsNullable();
.....
builder.Build();
}
}