سؤال

With code first EF4 (using CTP5) I can add a single navigation property along with the foreign key and it will respect the naming and only add the foreign key to the table a single time. If I then go and add a second property of the same type, it breaks it down into 4 columns on the table instead of just two.

Sample code:

With this model, I get a single property added to the AdapterFrameCapability table for PressType named PressTypeID.

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

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

    public virtual PressType PressType { get; set; }
}

This is the setup I want to model, but it results in 4 columns being created in the table, one each for FromPressTypeID, FromPressTypeFromPressTypeID, ToPressTypeID and ToPressTypePressTypeID. Ideally I'd just like a column for FromPressTypeID and ToPressTypeID. What am I doing wrong here?

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; }
}
هل كانت مفيدة؟

المحلول

It's one of those scenarios that you need to drop down fluent API to get the desired schema:

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 cascade delete off on one of the associations is intentional because otherwise SQL Server would throw out the following error:

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.

So we need to switch it off on one of the associations like the way I did in the code.

نصائح أخرى

I thought you were suppose to use the data annotation attribute

[ForeignKey("FromPressTypeId")]

etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top