EF using code first with a one-to-many relationship creating duplicate foreign keys

I use the following classes for a one-to-many relationship:

public class Supplier
{
    public Supplier()
    {
        SupplierId = Guid.NewGuid();
    }

    public Guid SupplierId { get; set; }
    [Required]
    public string Name { get; set; }

    [Required]
    public virtual Address Address { get; set; }

    public virtual ICollection<Contact> Contacts { get; set; }
}

public class Contact
{
    public Contact()
    {
        ContactId = Guid.NewGuid();
    }

    public Guid ContactId { get; set; }

    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }

    [Required]
    public Guid SupplierId { get; set; }
    [ForeignKey("SupplierId")]
    public virtual Supplier Supplier { get; set; }
}

I use ASP.NET MVC 4 and after creating a new contact, the provider is transferred to querystring and added to the Contact me form as a hidden field:

@Html.HiddenFor(model => model.SupplierId)

Contact SupplierId Guid . , "" , "Provider_SupplierId", NULL. , , "" "Supplier_SupplierId", "SupplierId" , . , , , Contact.Supplier_SupplierId NULL. , SupplierId Supplier_SupplierId Contact, .Contacts Contact.

:

CREATE TABLE [dbo].[Contacts] (
    [ContactId]           UNIQUEIDENTIFIER NOT NULL,
    [FirstName]           NVARCHAR (MAX)   NOT NULL,
    [LastName]            NVARCHAR (MAX)   NOT NULL,
    [Supplier_SupplierId] UNIQUEIDENTIFIER NULL,
    CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
    CONSTRAINT [FK_dbo.Contacts_dbo.Suppliers_SupplierId] FOREIGN KEY ([SupplierId]) REFERENCES [dbo].[Suppliers] ([SupplierId]),
    CONSTRAINT [FK_dbo.Contacts_dbo.Suppliers_Supplier_SupplierId] FOREIGN KEY ([Supplier_SupplierId]) REFERENCES [dbo].[Suppliers] ([SupplierId])
);

- , 2 ? , SupplierId?

+5
1

( ):

modelBuilder.Entity<Contact>()
    .HasRequired(r => r.Supplier)
    .WithMany()
    .HasForeignKey(f => f.SupplierId)
    .WillCascadeOnDelete(false);

:

modelBuilder.Entity<Contact>()
    .HasRequired(r => r.Supplier)
    .WithMany(s => s.Contacts)
    .HasForeignKey(f => f.SupplierId)
    .WillCascadeOnDelete(false);

EF Supplier.Contacts , " " Supplier Contact - .

+6

All Articles