EF 核心无法创建 Table,sql 语法错误

EF core can't create Table, error in sql syntax

我是 Entity framework 的新手,我不明白为什么它在 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

        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 模型构建器配置并显式映射关系。