c# - EF核心无法创建表,sql语法错误
问题描述
我是 Entity 框架的新手,我不明白为什么它给我一个 sql 语法错误,我认为使用 EFCore 的全部目的是处理 sql 语法并将所有 sql 查询抽象掉
这是我的模型:
class Block
{
public BlockHeader Header {get ;}
public List<Transaction> Transactions {get;}
public Block(List<Transaction> transactions, BlockHeader header)
{
Transactions= transactions;
Header=header;
}
public Block(){
}
}
public class BlockHeader
{
public byte[] Hash {get ;}
public byte[] PreviousHash { get; }
public DateTime timestamp { get; }
public int version{ get; }
public byte[] MerkleRoot{ get; }
public int SequenceNumber {get ; private set;}
public BlockHeader (byte[] previoushash,int sequencenumber,List<Transaction> transactions)
{
timestamp = DateTime.Now;
PreviousHash = previoushash;
version = 1;
SequenceNumber = sequencenumber;
MerkleRoot = ComputeMerkleRoot(transactions);
Hash = ComputeBlockHash();
}
这是我的数据库上下文类
class BlockchainDB : DbContext
{
public BlockchainDB()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;database = Blockchain ;user = root ; password = password");
}
protected override void OnModelCreating(ModelBuilder builder){
builder.Entity<Block>(e => e.HasNoKey());
}
}
当我添加迁移时,它会成功添加,但是当我使用此命令更新数据库时
dotnet ef database update
它输出此错误:
Failed executing DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE `Block` (
);
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 3
解决方案
EFCore 实体需要设置器,否则不会设置引用。
我建议你写这样的东西来确保封装
public class Block
{
protected Block()
{
// empty constructor needed for EF Core
}
// Navigation properties
public virtual BlockHeader BlockHeader {get; private set;}
// For collections
private readonly List<ChildEntity> _children = new List<ChildEntity>();
public virtual IReadOnlyList<ChildEntity> Children => _children.ToList();
// Encapsulated Business logic constructor
public Block(BlockHeader header, List<ChildEntity> children)
{
_children = children;
BlockHeader = header;
}
}
或者,您可以通过实体核心框架使用流利的 api 模型构建器配置并显式映射关系。
推荐阅读
- mysql - 加入日期范围
- javascript - 使用 React Hooks 获取数据 - 无法读取未定义的属性“地图”
- python - StatsModels 公式多项式回归与 numpy polyfit 系数不匹配
- c# - 在选择构造函数时发现 Moq 库中的潜在错误
- r - 更改 ggplot 样式,如 python plot
- selenium - Selenium Google 登录块
- angular - Ionic 4 ion-tabs - 错误错误:未捕获(承诺):错误:无法匹配任何路由。网址段:
- javascript - Google 表格脚本:TypeError:在对象电子表格中找不到函数 newFilterCriteria
- python-3.x - 如何从 Applescript => Module Not Found Errors 运行 Python(使用导入的模块)
- scylla - 由于存储 I/O 错误,Scylla 节点关闭