C# EFCore选择了错误的列名
在使用VSCode的教程之后,我创建了一个API,其中包含C# EFCore选择了错误的列名,c#,entity-framework,.net-core,entity-framework-core,ef-core-2.0,C#,Entity Framework,.net Core,Entity Framework Core,Ef Core 2.0,在使用VSCode的教程之后,我创建了一个API,其中包含.Net core和EFCore 我有很多MySQL数据库的模型,因为我正在用asp.NETWebAPI将我的EF6迁移到.NETCore,所以我只是复制和粘贴,以避免大量工作(再次) 当我尝试执行一个简单的Get时,EFCore将连接两列不同的表: 控制器用户 [Route("v1/[controller]")] public class UserController : Controller { private readon
.Net core
和EFCore
我有很多MySQL数据库的模型,因为我正在用asp.NETWebAPI
将我的EF6
迁移到.NETCore
,所以我只是复制和粘贴,以避免大量工作(再次)
当我尝试执行一个简单的Get
时,EFCore将连接两列不同的表:
控制器用户
[Route("v1/[controller]")]
public class UserController : Controller
{
private readonly IntentContext _context;
public UserController(IntentContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<user> GetAll()
{
return _context.user.ToList();
}
}
请注意,u.account\u typeid
字段实际上不存在。它是user
表的account\u type
和account\u type
表的id
的串联
为什么会这样
非常感谢并抱歉我的英语流利这在EF核心文档的一节中进行了解释:
如果找不到外键属性,则将使用名称引入阴影外键属性
您需要通过以下任一数据批注为用户.account\u type
导航属性指定FK属性:
[ForeignKey("id_account_type")]
public virtual account_type account_type { get; set; }
或fluent API:
modelBuilder.Entity<user>()
.HasOne(e => e.account_type)
.WithMany(e => e.user)
.HasForeignKey(e => e.id_account_type);
modelBuilder.Entity()
.HasOne(e=>e.account\u类型)
.WithMany(e=>e.user)
.HasForeignKey(e=>e.id\u账户类型);
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (140ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT `u`.`id`, `u`.`Id_account_type`, `u`.`account_typeid`, `u`.`create_time`, `u`.`password`, `u`.`update_time`, `u`.`user_status`, `u`.`username`
FROM `user` AS `u`
MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'u.account_typeid' in 'field list' ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column **'u.account_typeid'** in 'field list'
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
//A lot of exceptions generated
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred in the database while iterating the results of a query for context type 'IntentAPI.Models.IntentContext'.
MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'u.account_typeid' in 'field list' ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'u.account_typeid' in 'field list'
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
[ForeignKey("id_account_type")]
public virtual account_type account_type { get; set; }
modelBuilder.Entity<user>()
.HasOne(e => e.account_type)
.WithMany(e => e.user)
.HasForeignKey(e => e.id_account_type);