代码之家  ›  专栏  ›  技术社区  ›  SamuraiJack

如何在实体框架中创建双向导航属性?

  •  0
  • SamuraiJack  · 技术社区  · 6 年前

    有一个 Cargo 具有标识的类/表 CargoID 有一个 ContainerIn 包含的类/表

    每件货物可以有1个或0个相应的集装箱条目。 Cargo.ContainerIn --->应该给我 集装箱 进入 ContainerIn.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; }
    }
    

    容器子类:

    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 货物等级。

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

    现在我得到: enter image description here

    2 回复  |  直到 6 年前
        1
  •  2
  •   GregH    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 概述的数据注释 here

        2
  •  0
  •   Just code    6 年前

    无法确定 “PisMark3。型号.货物.货物'. 这个协会的主要目的 必须使用关系fluent API显式配置 或数据注释

    这是告诉你要定义你的关系,因为它不能理解这种关系。

    你要找的是 一对零或一关系 link

    这是你的模特,

     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 CompanyUserNameContainIn { get; set; }
        }
    
        public class ContainerIn
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int ContainerInID { get; set; }        
            public int LoadStatus { get; set; }        
            public int CargoID { get; set; }        
            public virtual Cargo Cargo { get; set; }
        }
    

    这是你的flent api代码,

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {           
                modelBuilder.Entity<Cargo>()
                            .HasOptional(s => s.CompanyUserNameContainIn) 
                            .WithRequired(ad => ad.Cargo); 
            }
    

    这告诉entityframework它有可选的 公司用户名 在里面 货物 货物 在里面 集装箱

    你可以在我提供的链接中详细阅读,它有一个很好的学生和地址的例子。

    编辑:

    当您想使用identityDBContext时,您可以如下修改您的代码

    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
        public class ApplicationUser : IdentityUser
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here
                return userIdentity;
            }
        }
    
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
        {
    
            public virtual DbSet<Cargo> Cargo { get; set; }
            public virtual DbSet<ContainerIn> ContainerIn { get; set; }
    
            public ApplicationDbContext()
                : base("DefaultConnection")
            {
            }
    
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {           
                modelBuilder.Entity<Cargo>()
                            .HasOptional(s => s.CompanyUserNameContainIn) 
                            .WithRequired(ad => ad.Cargo);
    
                modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
                modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
                modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    
            }
    
        }