2016-12-18 3 views
0

Ich versuche, ein Projekt mit Code zuerst einzurichten, aber ich habe ein Problem mit Fremdschlüsseln. Ich habe eine wirklich einfache Klasse mit einer Navigationseigenschaft. Ich habe versucht, den Spaltennamen des Fremdschlüssels zu setzen, aber es funktioniert nicht, stattdessen wird eine andere Spalte erstellt.MVC Fremdschlüssel Bindung

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; } 
} 

In der Migrationsdatei Ich habe:

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); 

Wie Sie eine Account_AccountId Spalte erstellt wird, sehen kann, aber ich würde meine AccountId Spalte mag stattdessen als Fremdschlüssel verwendet werden.

[Bearbeiten]

ich gefunden habe, dass einige Zeilen, die ich in der OnModelCreating Funktion hinzugefügt sind verantwortlich:

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

ich dort angegebene auch Spalte, die als Fremdschlüssel zu verwenden, aber irgendwie Hinzufügen Dies führt dazu, dass eine neue Spalte erstellt wird.

Antwort

0

Ich fand die Lösung, ich musste einen Parameter in die Methode WithMany aufnehmen, damit es funktioniert.

 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);