【发布时间】:2018-09-09 14:58:34
【问题描述】:
我正在将应用程序转换为 Entity Framework Core,但在获取我的两个模型类之间的外键关系时遇到了麻烦。这些类是这样设置的(注意,BaseEntity 上声明了 Guid Id 字段):
public class Crt : BaseEntity
{
[Required]
public Guid FacId { get; set; }
[Required]
public string Code { get; set; }
[ForeignKey("ActiveCrtChk")
public Guid? ActiveCrtChkId { get; set; }
public string Description { get; set; }
public string Device { get; set; }
#region navigation properties
public CrtChk ActiveCrtChk;
public List<CrtChk> CartChecks;
#endregion
}
public class CrtChk : BaseEntity
{
[Required]
public Guid CrtId { get; set; }
[Required]
public string Device { get; set; }
[Required]
public Guid OutSysUsrId { get; set; }
[Required]
public DateTime OutSysDateTime { get; set; }
public Guid? InSysUsrId { get; set; }
public DateTime? InSysDateTime { get; set; }
[Required]
public string Type { get; set; }
#region navigation properties
public Crt Cart { get; set; }
public Usr OutSysUsr { get; set; }
public Usr InSysUsr { get; set; }
public List<CrtEvt> CartEvents { get; set; }
#endregion
}
关系背后的想法是,一个Crt 可以有许多CrtChk 记录,但Crt 还存储了活动 CrtChk 记录的Id。
当我运行迁移时,它会生成 Crt 和 CrtChk 之间的所有外键关系,但没有为 ActiveCrtChkId 字段生成外键。
通过阅读this post,我了解到ActiveCrtChkId 属性上的ForeignKey 属性与ActiveCrtChk 导航属性的名称相同,我应该在迁移中获得外键约束。
我在这里错过了什么?
编辑
在修复了将Crt 导航属性声明为字段的错误后,我在尝试创建迁移时偶然发现了一个新错误。
Unable to determine the relationship represented by navigation property 'Crt.ActiveCrtChk' of type 'CrtChk'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
我以为ForeignKey 属性是手动配置关系?我需要使用 Fluent API 来创建关系吗?如果是这样,我如何使用 Fluent API 建立既可以是一对一(Crt 到 ActiveCrtChk)也可以是一对多(所有与 Crt 关联的 CrtChks)的关系?
【问题讨论】:
-
“我在这里缺少什么?” -
Crt导航属性不是属性,而是字段 :) -
@ivanStoev Duh!感谢您指出了这一点!正确设置导航属性后,我收到一个新错误,请参阅我的编辑。
-
不要让属性为空。
标签: c# entity-framework ef-code-first migration entity-framework-core