0
먼저 코드를 사용하여 프로젝트를 설정하려고하지만 외래 키에 문제가 있습니다. 네비게이션 속성을 가진 정말 간단한 클래스가 있습니다. 외래 키 열 이름을 설정하려고했지만 작동하지 않는 대신 다른 열이 대신 만들어집니다. 마이그레이션 파일에서 MVC 외래 키 바인딩
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);
}
그러면 새 열이 만들어집니다.