首页 > 解决方案 > 如何在实体框架中创建双向导航属性?

问题描述

有一个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; } inCargo 类。我仍然得到:

`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.`

编辑:OnModelCreatingApplicationDbContext课堂上添加了。

 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>());
        }
    .... 

现在我得到: 在此处输入图像描述

标签: c#asp.net-mvcentity-frameworklinqentity-framework-6

解决方案


你很接近。我认为您想要以下内容:

    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概述的数据注释


推荐阅读