ridermansb
ridermansb

Reputation: 11059

Fluent API for navigation property in the two ways

Classes

public class ProductType
{
    public Guid ID { get; set }
    public string Name { get; set }
    public ICollection<ProductCategory> Categories { get; set }
}

public class ProductCategory
{
    public Guid ID { get; set }
    public string Name { get; set }
    public ProductType ProductType { get; set; }
}

Configuration

ProductTypeConfiguration

HasMany(p => p.Categories).WithRequired().WillCascadeOnDelete(false);

Question

Note the properties Categories and ProductType

The relationship is one (ProductType) to many (ProductCategory), however, a ProductCategory is associated with a single ProductType!

In my database it is creating two FKS!! How would the configuration (using FluentAPI) for this type of situation??

Thanks!!!

Upvotes: 0

Views: 1207

Answers (1)

Slauma
Slauma

Reputation: 177133

HasMany(p => p.Categories)
    .WithRequired(c => c.ProductType) // specify inverse navigation property here
    .WillCascadeOnDelete(false);

If you omit the lambda for the navigation property in WithRequired EF assumes that Category.ProductType belongs to another second relationship - which is the reason for the second foreign key in your database table.

Upvotes: 7

Related Questions