这是一个奇怪的问题。我的实体框架核心项目将表格和ID合并为一列,如下所示:MonsterListMonsterId
这是错误:
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'MonsterListMonsterId'
这是产生错误的控制器:
var treasuresByMonster = await _context.MonsterTreasures.Where(q => q.MonsterId == id).ToListAsync();
显然,该列称为MonsterId。不是MonsterListMonsterId。
这是MonsterList类:
public class MonsterList
{
public MonsterList()
{
MonsterTreasures = new HashSet<MonsterTreasures>();
}
public Guid MonsterId { get; set; }
public string MonsterText { get; set; }
public virtual ICollection<MonsterTreasures> MonsterTreasures { get; set; }
}
这是MonsterTreasure类:
public partial class MonsterTreasures
{
public Guid TreasureId { get; set; }
public Guid? MonsterId { get; set; }
public string TreasureText { get; set; }
public MonsterList MonsterList { get; set; }
}
和上下文类:
modelBuilder.Entity<MonsterTreasures>(entity =>
{
entity.HasKey(e => e.TreasureId);
entity.HasOne(e => e.MonsterList)
.WithMany(m => m.MonsterTreasures);
entity.ToTable("MonsterTreasures");
entity.Property(e => e.TreasureId)
.HasColumnName("TreasureId");
entity.Property(e => e.MonsterId)
.HasColumnName("MonsterId");
entity.Property(e => e.TreasureText)
.HasColumnName("TreasureText");
});
什么是正确的解决方案?
谢谢!
问题在这里
public Guid? MonsterId { get; set; }
public MonsterList MonsterList { get; set; }
名称“ MonsterId”与任何EF Core常规FK属性名称都不匹配:
<navigation property name><principal key property name>
<navigation property name>Id
<principal entity name><principal key property name>
<principal entity name>Id
因此,EF Core不会将其视为FK属性,而是假定异常消息中的阴影属性/列具有默认名称。
为了解决此问题,您必须通过[ForeignKey]
在FK属性上指定导航属性名称的数据注释来显式地映射它:
[ForeignKey(nameof(MonsterList)]
public Guid? MonsterId { get; set; }
public MonsterList MonsterList { get; set; }
或在导航属性上指定FK属性的名称:
public Guid? MonsterId { get; set; }
[ForeignKey(nameof(MonsterId)]
public MonsterList MonsterList { get; set; }
或HasForeignKey
在此处使用Fluent API:
entity.HasOne(e => e.MonsterList)
.WithMany(m => m.MonsterTreasures)
.HasForeignKey(e => e.MonsterId); // <--
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句