我正在开发一个ASP.NET Core前端以连接到我的Google Cloud SQL MySQL数据库。

我有以下模型:

namespace shipping.Models
{
    public class ShippingAppContext : DbContext
    {
        public ShippingAppContext(DbContextOptions<ShippingAppContext> options) : base(options) { }

        public DbSet<Ship> ships { get; set; }
        public DbSet<Company> companies { get; set; }
    }

    public class Ship
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual Company Company { get; set; }
    }

    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Ship> Ships { get; set; }
    }
}


然后在显示_context.ships.ToListAsync()ship.Name的剃须刀页面中遍历ship.Company.Name

我的数据库如下:

MySQL [shipping]> show tables;
+--------------------+
| Tables_in_shipping |
+--------------------+
| companies          |
| ships              |
+--------------------+
MySQL [shipping]> select * from ships;
+------+-----------------+---------+
| Id   | Name            | Company |
+------+-----------------+---------+
|    1 | Eugen Maersk    |       1 |
|    2 | Madrid Maersk   |       1 |
|    3 | COSCO Vancouver |       4 |
|    4 | COSCO Rotterdam |       4 |
+------+-----------------+---------+
MySQL [shipping]> select * from companies;
+------+----------------------------------------------+
| Id   | Name                                         |
+------+----------------------------------------------+
|    1 | A.P. Moller–Maersk Group                     |
|    2 | Mediterranean Shipping Company S.A. (MSC)    |
|    3 | CMA CGM Group                                |
|    4 | China Ocean Shipping (Group) Company (COSCO) |
+------+----------------------------------------------+


仅显示ship.Name即可正常工作,但是一旦尝试显示ship.Company.Name,我就会得到:MySqlException: Unknown column 's.CompanyId' in 'field list'

我已经进行了搜索,并且在项目中的任何地方都未引用CompanyIdships表不包含CompanyId列。

我想这可能是因为我直接在sql实例中创建了表和数据,而不是使用dotnet ef创建数据库并上传了它。但是我认为这在Google Cloud SQL上是不可能的吗?

如何从模型中使efcore做INNER JOIN

最佳答案

如果您是手动创建数据库,则可以手动添加具有FOREIGN KEY约束关系(FK_ships_companies_CompanyId)的表架构,以便可以查询相关数据,例如:

var result = _context.ships.Include(a=> a.Company).ToList();

关于mysql - MySql和 Entity Framework 核心-MySqlException:“字段列表”中的未知列“s.CompanyId”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57255844/

10-09 21:18