MVC外键绑定

时间:2016-12-18 19:29:52

标签: asp.net-mvc ef-code-first ef-migrations

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

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 个答案:

答案 0 :(得分:0)

我找到了解决方案,我必须在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);