2010-12-13 29 views
12

Với mã EF4 đầu tiên (sử dụng CTP5) tôi có thể thêm một thuộc tính điều hướng cùng với khóa ngoài và nó sẽ tôn trọng việc đặt tên và chỉ thêm khóa ngoài vào bảng một lần duy nhất. Nếu tôi sau đó đi và thêm một thuộc tính thứ hai cùng loại, nó sẽ chia nhỏ nó thành 4 cột trên bảng thay vì chỉ hai.Làm thế nào tôi có thể thiết lập hai thuộc tính điều hướng cùng loại trong Entity Framework

Mẫu mã:

Với mô hình này, tôi nhận được một tài sản được bổ sung vào bảng AdapterFrameCapability cho PressType tên PressTypeID duy nhất.

public class AdapterFrameCapability 
{ 
    [Key] 
    public int AdapterFrameCapabilityID { get; set; } 

    [Required] 
    public int PressTypeID { get; set; } 

    public virtual PressType PressType { get; set; } 
} 

Đây là thiết lập Tôi muốn để mô hình, nhưng nó kết quả trong 4 cột được tạo ra trong bảng, một trong mỗi cho FromPressTypeID, FromPressTypeFromPressTypeID, ToPressTypeID và ToPressTypePressTypeID. Lý tưởng nhất là tôi chỉ muốn một cột cho FromPressTypeID và ToPressTypeID. Tôi làm gì sai ở đây?

public class AdapterFrameCapability 
{ 
    [Key] 
    public int AdapterFrameCapabilityID { get; set; } 

    [Required] 
    public int FromPressTypeID { get; set; } 

    [Display(Name = "From Press Type")] 
    public virtual PressType FromPressType { get; set; } 

    [Required] 
    public int ToPressTypeID { get; set; } 

    [Display(Name = "To Press Type")] 
    public virtual PressType ToPressType { get; set; } 
} 

Trả lời

14

Đó là một trong những kịch bản mà bạn cần phải thả xuống fluent API để có được schema mong muốn:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<AdapterFrameCapability>() 
       .HasRequired(afc => afc.FromPressType) 
       .WithMany() 
       .HasForeignKey(afc => afc.FromPressTypeID) 
       .WillCascadeOnDelete(true); 

    modelBuilder.Entity<AdapterFrameCapability>() 
       .HasRequired(afc => afc.ToPressType) 
       .WithMany() 
       .HasForeignKey(afc => afc.ToPressTypeID) 
       .WillCascadeOnDelete(false); 
} 

Switching thác xóa đi trên một trong những hiệp hội là cố ý vì khác SQL Server sẽ phát ra lỗi sau:

Introducing FOREIGN KEY constraint 'AdapterFrameCapability_ToPressType' on table 'AdapterFrameCapabilities' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint.

Vì vậy, chúng tôi cần phải tắt nó trên một trong các hiệp hội như cách tôi đã làm trong mã.

0

anh nghĩ em đã giả sử dụng thuộc tính dữ liệu chú thích

[ForeignKey("FromPressTypeId")] 

, vv

Các vấn đề liên quan