如何解决实体框架正在组合我的表名和ID名
这是一个奇怪的问题。我的实体框架核心项目将表格和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 conventional FK property names不匹配:
<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属性,而是假定异常消息中的阴影属性/列具有默认名称。
为了解决该问题,您必须通过在导航属性名称上指定FK属性的[ForeignKey]
数据注释来明确映射它:
[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); // <--
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。