c# - 如何在实体框架中创建双向导航属性?
问题描述
有一个Cargo
具有身份的类/表CargoID
有一个ContainerIn
类/表包含 CargoID
每个 Cargo 可以有 1 个或 0 个对应的容器条目。我正在尝试创建这样的导航属性。
Cargo.ContainerIn
--->应该给我相关ContainerIn
的条目
ContainerIn.Cargo
--->应该给我相关Cargo
的条目
货物类别:
public class Cargo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CargoID { get; set; }//SerialNo
[Required]
public DateTime DateOfPassage { get; set; }
public string CompanyUserName { get; set; }
public virtual ContainerIn ContainerIn { get; set; }
}
ContainerIn 子类:
public class ContainerIn
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContainerInID { get; set; }
public int CargoID { get; set; }
public virtual Cargo Cargo { get; set; }
public int LoadStatus { get; set; }
}
我也尝试过添加public int ContainerInID { get; set; } in
Cargo 类。我仍然得到:
`Unable to determine the principal end of an association between the types 'PisMark3.Models.Cargo.ContainerIn' and
'PisMark3.Models.Cargo.Cargo'.
The principal end of this association must be explicitly configured
using either the relationship fluent API or data annotations.`
编辑:
我OnModelCreating
在 ApplicationDbContext
课堂上添加了。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PisMark3.Models.Cargo.Cargo>()
.HasOptional(s => s.ContainerIn)
.WithRequired(ad => ad.Cargo);
}
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
// Database.SetInitializer<ApplicationDbContext>(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());
}
....
解决方案
你很接近。我认为您想要以下内容:
public class Cargo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CargoID { get; set; }//SerialNo
[Required]
public DateTime DateOfPassage { get; set; }
public string CompanyUserName { get; set; }
public int ContainerInId { get; set; } //need to define a foreign key. This is happening by naming convention in this case as with your `ContainerIn.CargoId` foreign key
public virtual ContainerIn ContainerIn { get; set; }
}
public class ContainerIn
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContainerInID { get; set; }
public int CargoID { get; set; }
public virtual Cargo Cargo { get; set; }
public int LoadStatus { get; set; }
}
请注意,这是一个循环引用,如果可能的话应该避免使用,但是肯定有一些有效的用例。只是想我会大声疾呼。
如果您不想遵守命名约定,可以使用此处ForeignKey
概述的数据注释
推荐阅读
- javascript - 为什么 forEach 可以与 e.target.children 一起使用,但不能与 getElementById 孩子一起使用?
- javascript - 点击后如何再次进行 v-for 更新?
- c# - 玩家在相机方向移动并且能够在没有动画的情况下跳跃
- reactjs - 如何更改 VictoryTooltip 的 fontStyle 和边框颜色
- .net - 在 .NET Core MVC 中从一个模型访问另一个模型的数据
- swift - 无法识别的字体系列“FontAwesome5Free-Solid”
- python - 有没有办法防止反斜杠('\\')重复为'\\\\'?
- r - 无法使用 gganimate 为 geom_line 和 geom_point 设置动画
- laravel - 现在如何使用时间日期更新数据
- reactjs - 在 Aurelia 框架内的 React 中使用 redux