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

MVC外键绑定

  •  0
  • user3044142  · 技术社区  · 8 年前

    我试图先使用代码设置一个项目,但外键有问题。我有一个非常简单的带有导航属性的类。我试图设置外键列名,但不起作用,而是创建了另一列。

    public class Point
    {
        public int PointId { get; set; }
    
        public int AccountId { get; set; }
    
        [ForeignKey("AccountId")]
        public virtual Account Account { get; set; }
    
        public Decimal Balance { get; set; }
        public DateTime Date { get; set; }
        public int CategoryId { get; set; }
    
        [Required]
        public virtual Category Category { get; set; }
    }
    

    在迁移文件中,我有:

    CreateTable(
                "dbo.Points",
                c => new
                    {
                        PointId = c.Int(nullable: false, identity: true),
                        AccountId = c.Int(nullable: false),
                        Balance = c.Decimal(nullable: false, precision: 18, scale: 2),
                        Date = c.DateTime(nullable: false),
                        CategoryId = c.Int(nullable: false),
                        Account_AccountId = c.Int(),
                    })
                .PrimaryKey(t => t.PointId)
                .ForeignKey("dbo.Accounts", t => t.AccountId, cascadeDelete: true)
                .ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true)
                .ForeignKey("dbo.Accounts", t => t.Account_AccountId)
                .Index(t => t.AccountId)
                .Index(t => t.CategoryId)
                .Index(t => t.Account_AccountId);
    

    正如你所看到的 Account_AccountId 列已创建,但我希望 AccountId 列用作外键。

    [编辑]

    我发现我在 OnModelCreating 职能部门负责:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<Point>()
                .HasRequired(c => c.Account)
                .WithMany().HasForeignKey(e => e.AccountId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Category>()
                .HasRequired(s => s.Account)
                .WithMany().HasForeignKey(e => e.AccountId)
                .WillCascadeOnDelete(true);
        }
    

    我也在那里指定了要用作外键的列,但不知何故,添加此项会导致创建一个新列。

    1 回复  |  直到 8 年前
        1
  •  0
  •   user3044142    8 年前

    我找到了解决方案,我必须在WithMany方法中包含一个参数才能让它工作。

            modelBuilder.Entity<Point>()
                .HasRequired(c => c.Account)
                .WithMany(e=> e.Points).HasForeignKey(e => e.AccountId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Category>()
                .HasRequired(s => s.Account)
                .WithMany(e=>e.Categories).HasForeignKey(e => e.AccountId)
                .WillCascadeOnDelete(true);